Defining functions using backslash in c++

时间:2015-10-30 22:49:51

标签: c++ macros

I saw people using backslash when they define functions in Macros as:

#define ClassNameNoDebug(TypeNameString)                                    \
    static const char* typeName_() { return TypeNameString; }                 \
    static const ::Foam::word typeName

I did a very easy test. But I got a bunch of errors. The testing code is as follows: In my testmacro.h file:

#define declearlarger(first,second)                                                          \
    double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}

In my main() function:

int second =2;
int first =1;

cout << declearlarger(first,second) << endl;

The errors are:

/home/jerry/Desktop/backslash/backslash_test/testmacro.h:7: error: expected primary-expression before 'double'
     double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}
     ^
/home/jerry/Desktop/backslash/backslash_test/testmacro.h:7: error: expected ';' before 'double'
     double whichislarger(double first,double second){ return (first>second) ? fisrt : second;}
     ^
/home/jerry/Desktop/backslash/backslash_test/main.cpp:24: error: expected primary-expression before '<<' token
     cout << declearlarger(first,second) << endl;
                                         ^

That concludes all my testing errors. Can anyone give some suggestions why these errors pop up?

1 个答案:

答案 0 :(得分:3)

You're trying to use a function definition (generated by your macro) inside an expression. C++ does not allow such a thing. You could instead define your macro to be

#define declearlarger(first,second) \
        (((first)>(second)) ? (first) : (second))

and then it would work. Also note that none of the errors come from the backslash, they are all generated because of the function definition/expression clash.