Variadic recursive preprocessor macros - is it possible?

前端 未结 6 871
一生所求
一生所求 2020-11-28 07:11

I\'ve run into a little theoretical problem. In a piece of code I\'m maintaining there\'s a set of macros like

#define MAX_OF_2(a, b)       (a) > (b) ? (a         


        
6条回答
  •  渐次进展
    2020-11-28 08:08

    First, macros don't expand recusrsively. Although, macros can have reentrance by creating a macro for each recursion level and then deducing the recursion level. However, all this repetition and deducing recursion, is taken care of by the Boost.Preprocessor library. You can therefore use the higher order fold macro to calculate the max:

    #define MAX_EACH(s, x, y) BOOST_PP_IF(BOOST_PP_GREATER_EQUAL(x, y), x, y)
    #define MAX(...) BOOST_PP_SEQ_FOLD_LEFT(MAX_EACH, 0, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) 
    
    MAX(3, 6, 8) //Outputs 8
    MAX(4, 5, 9, 2) //Outputs 9
    

    Now, this will understand literal numbers between 0-256. It wont work on C++ variables or expression, because the C preprocessor doesn't understand C++. Its just pure text replacement. But C++ provides a feature called a "function" that will work on C++ expressions, and you can use it to calculate the max value.

    template
    T max(T x, T y)
    {
        return x > y ? x : y;
    }
    
    template
    auto max(X x, T ... args) -> decltype(max(x, max(args...)))
    {
        return max(x, max(args...));
    }
    

    Now, the code above does require a C++11 compiler. If you are using C++03, you can create multiple overloads of the function in order to simulate variadic parameters. Furthermore, we can use the preprocessor to generate this repetitive code for us(thats what it is there for). So in C++03, you can write this:

    template
    T max(T x, T y)
    {
        return x > y ? x : y;
    }
    
    #define MAX_FUNCTION(z, n, data) \
    template \
    T max(T x, BOOST_PP_ENUM_PARAMS(n, T x)) \
    { \
        return max(x, max(BOOST_PP_ENUM_PARAMS(n, x)));\
    }
    
    BOOST_PP_REPEAT_FROM_TO(2, 64, MAX_FUNCTION, ~) 
    

提交回复
热议问题