C++ preprocessor conditional parameter

前端 未结 4 793
抹茶落季
抹茶落季 2021-01-18 08:12

Please note C++03! any C++11 solutions are not good for me, but do post them just for knowledge sake.

I know the preprocessor can do things like:

#de         


        
4条回答
  •  无人及你
    2021-01-18 09:12

    You can do this with the preprocessor if the domain of values for the conditional parameter is well-known (and preferably small). For example, supposing the parameter can only have the values 0 and 1:

    #define DOIT_0(X)
    #define DOIT_1(X) X
    #define CONCAT_(X, Y) X ## Y
    #define MAYBE(X) CONCAT_(DOIT_, X)
    
    #define BAR(X) MAYBE(X)(  cout<<"hi"<

    Live on coliru.

    Beware of unprotected commas in the argument to BAR.

    For equality checks, again over a small range:

    #define CONCAT3_(X,Y,Z) X ## Y ## Z
    #define EQUAL_0_0(X) X
    #define EQUAL_1_1(X) X
    #define EQUAL_1_1(X) X
    #define EQUAL_0_1(X)
    #define EQUAL_0_2(X)
    #define EQUAL_1_0(X)
    #define EQUAL_1_2(X)
    #define EQUAL_2_0(X)
    #define EQUAL_2_1(X)
    #define DO_IF_EQUAL(X, Y) CONCAT3_(EQUAL_, X, Y)
    
    #define BAR(X) DO_IF_EQUAL(X, 2) ( std::cout << "hi\n"; )
    

提交回复
热议问题