Is there a way to create a preprocessor macro for a function?

Is it possible to create a C ++ preprocessor macro based on the result of a function?

For example, I would like to dynamically save the height of the screen in the macro definition of the preprocessor:

#define SCREEN_HEIGHT   GetSystemMetrics(SM_CYVIRTUALSCREEN)

Then I want to use the result to set values ​​based on the height of the screen:

#if SCREEN_HEIGHT < 1200
    #define TOP_COORD     200
    #define BOTTOM_COORD  500
    #define LEFT_COORD    0
    #define RIGHT_COORD   1280
#else
    #define TOP_COORD     1100
    #define BOTTOM_COORD  1400
    #define LEFT_COORD    0
    #define RIGHT_COORD   1280
#endif

This does not work, since SCREEN_HEIGHT does not seem to be detected correctly.

Is there a better way to do this? Is it possible? I want to be able to get this screen height information in the header file, if possible, as this is part of a large piece of legacy code.

+2
source share
4 answers

. , , , , , #if .. . , .

+5

, . , , ? .

+2

. , sizeof ( - @Pubby ) . - , #if. .

, , . -, , .

, , , , .

+2
source

If it GetSystemMetricsis a macro, you can do it. If you GetSystemMetricswill constexpr, you can use the features.

But since it GetSystemMetricsis a normal function, you need to work with regular C ++.

struct system_metrics_ {
  int top, bottom, left, right;

  system_metrics_()
  {
    if (GetSystemMetrics(SM_CYVIRTUALSCREEN) < 1200) { /* first case */ }
    else { /* second case */ }
  }
};

// define this method outside the header
const system_metrics_& system_metrics() { static system_metrics_ sm; return sm; }

// legacy code
#define TOP_COORD     (system_metrics().top)
#define BOTTOM_COORD  (system_metrics().bottom)
#define LEFT_COORD    (system_metrics().left)
#define RIGHT_COORD   (system_metrics().right)
0
source

Source: https://habr.com/ru/post/1764179/


All Articles