简体   繁体   English

检查表达式是否为“ constexpr”

[英]Checking whether an expression is `constexpr`

C++17 adds constexpr if ( to choose if to compile a statement if the condition is a constexpr ) http://en.cppreference.com/w/cpp/language/if C ++ 17添加constexpr if(如果条件是constexpr,则选择是否编译一条语句) http://en.cppreference.com/w/cpp/language/if

Is there a trick to emulate a limited form of this construct in C++11 ? 有没有技巧可以模拟C ++ 11中此构造的有限形式?

If would need the following construct in a macro: 如果需要在宏中进行以下构造:

  #define ALLOCATE(x) if ({x is a constant}) allocate_n<x>() else allocate(x)

Supposing that you're using GCC or Clang, you can use the __builtin_constant_p() extension: 假设您使用的是GCC或Clang,则可以使用__builtin_constant_p()扩展名:

#define ALLOCATE(x) \
    __builtin_constant_p(x) \
        ? allocate_n<__builtin_constant_p(x) ? x : 0>() \
        : allocate(x)

See it live on Coliru 在Coliru上实时观看

Is there a trick to emulate a limited form of this construct in C++11 ? 有没有技巧可以模拟C ++ 11中此构造的有限形式?

The best I can imagine is substitute 我能想象的最好的替代品

if constexpr ( cond ) statment-1 else statement-2;

with

foo<cond>( /* ? */ );

where foo() is defined as follows foo()的定义如下

template <bool>
void foo (/* ? */);

template <>
void foo<true> (/* ? */)
 { /* statement-1 */ }

template <>
void foo<false> (/* ? */)
 { /* statement-2 */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM