function that takes only literal integers

后端 未结 3 1900
一生所求
一生所求 2021-01-03 22:30

I\'m looking for a way to simulate certain overloaded GCC built-ins in C++. The built-ins are similar to these:

__builtin_foo(char *a, signed int b);
__buil         


        
3条回答
  •  滥情空心
    2021-01-03 22:36

    You can sort of simulate it using a macro and the GCC intrinsic __builtin_constant_p

    constexpr int foo(int i) { return i; }
    
    #define FOO(i) do { \
      static_assert(__builtin_constant_p(i), "Not a constant"); \
      foo(i); \
    } while (false)
    

    This will allow FOO(1) to compile, but not int i = 1; FOO(i);

    However, the result of __builtin_constant_p depends on the optimisation level, at higher levels of optimisation const variables are treated as constants, so it doesn't only accept literals.

    Of course if you're willing to allow constant-expressions, not just literals, then all you have to do is use the variable in a context that requires a constant-expression, such as a static assertion or a non-type template argument.

提交回复
热议问题