How to print result of a compile-time calculation in C++?

后端 未结 5 830
刺人心
刺人心 2021-01-01 22:27

I\'ve wrote several constexpr functions and use them in static_asserts to control some resource limits. But I\'d like to not only enforce compile-time predicate but also to

5条回答
  •  无人及你
    2021-01-01 23:17

    There's an answer by @je4d (https://stackoverflow.com/a/13465643/3353857),
    which works for msvc, gcc, clang, and lots of compilers on godbolt except for the ancient gcc 4.1.2

    #define strcat_(x, y) x ## y
    #define strcat(x, y) strcat_(x, y)
    #define PRINT_VALUE(x) \
        template  \
        struct strcat(strcat(value_of_, x), _is); \
        static_assert(strcat(strcat(value_of_, x), _is)::x, "");
    
    
    #line 4242
    constexpr int PI_INT = __LINE__;  /*set the value*/
    
    PRINT_VALUE(PI_INT) /*print it*/
    

    It prints the value in the error message:

    :4244:1: error: incomplete type 'value_of_PI_INT_is<4242>' used in nested name specifier

提交回复
热议问题