C++ compile-time constant detection

后端 未结 3 1118
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 05:14

There\'re cases when a library source is available, and it has to support variable parameters in general, but in practice these parameters are commonly constants.

Th

3条回答
  •  我在风中等你
    2020-12-10 06:10

    is_const should be more reliable. On gcc-4.4 for example, the following:

    int k=0;
    printf("%d\n",is_const(k),is_const(k>0));
    

    prints:

    0,1
    

    GCC is quite ambitious folding constant expressions which are not integral constant expressions by the words of the standard. A potentially better definition of is_const could be:

    #define is_const(B)\
    (sizeof(chkconst::chk2(0+!!(B))) != sizeof(chkconst::chk2(0+!(B))))
    

    Aside from that, your technique is awesome, because I can finally write a SUPER_ASSERT macro which is checked during compilation if the assertion expression if compile-time and during runtime otherwise:

    #define SUPER_ASSERT(X) {BOOST_STATIC_ASSERT(const_switch_uint(X,1));assert(X);}
    

    I'll look into that const_switch_xxx() thing later. I have no idea how to implement another way, the deconstruct/reconstruct trick is brilliant.

提交回复
热议问题