#error inside of #define - Possible in C++ (generate error WHEN calling macro MyMacro IF some constant is not defined)?

StackOverflow https://stackoverflow.com/questions/23320743

Domanda

I want to define the macro, that based on some condition (existence of #define INITED, not the parameter of the macro) will return value, or generate compiler's error, like:

#error Not initialized!

I've tried (for myIdea.h):

#ifdef INITED
    #define MyMacro(x) x->method(); //something with x
#else
    #define MyMacro(x) #error Not initalized!
#endif

But that code generates error (not the one I wanted to) expected macro format parameter.

Note, that I don't want that code (working, but doing bit different thing):

#ifdef INITED
    #define MyMacro(x) x->method(); //something with x
#else
    #error Not initalized!
#endif

The code above will geneate error just when INITED won't be defined. I want to generate error only when I call to the MyMacro() AND INITED has not been yet defined.

I'm not the slave to the first code, but I want the result to work exactly the way I've described above (generate error WHEN calling macro MyMacro IF constant inited is not defined).

È stato utile?

Soluzione

This is not possible. The preprocessor is just a very simple thing, it does not parse nested macros like that. The second pound (#) would not be understood as a nested macro by the preprocessor. The argument is pretty much handled as raw string.

You could however look into static assert with C++11 and on instead of your #error directive. You would be writing then something like this:

#ifdef INITED
    #define MyMacro(x) x->method(); //something with x
#else
    #define MyMacro(x) static_assert(false, "Not initalized!");
#endif
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top