Is constexpr really needed?

后端 未结 6 2223
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 14:35

I have been looking at the new constexpr feature of C++ and I do not fully understand the need for it.

For example, the following code:

         


        
6条回答
  •  失恋的感觉
    2020-12-03 15:00

    constexpr allows the following to work:

    #include
    using namespace std;
    
    constexpr int n_constexpr() { return 3; }
    int n_NOTconstexpr() { return 3; }
    
    
    template
    struct Array { typedef int type[n]; };
    
    typedef Array::type vec_t1;
    typedef Array::type vec_t2; // fails because it's not a constant-expression
    
    static const int s_maxSize = n_NOTconstexpr();
    typedef Array::type vec_t3; // fails because it's not a constant-expression
    

    template arguments really do need to be constant-expressions. The only reason your example works is because of Variable Length Arrays (VLAs) - a feature that is not in standard C++, but might be in many compilers as an extension.

    A more interesting question might be: Why not put constexpr on every (const) function? Does it do any harm!?

提交回复
热议问题