how to initialize a constexpr reference

前端 未结 3 1650
余生分开走
余生分开走 2020-11-28 13:29

I am trying to initialize a constexpr reference with no success. I tried

#include 

constexpr int& f(int& x) // can defi         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 14:09

    So the problem is that a constexpr reference needs to bind to an object with static storage duration, which is covered in the draft C++11 standard: N3337 section 5.19 [expr.const] (emphasis mine):

    A reference constant expression is an lvalue core constant expression that designates an object with static storage duration or a function

    The draft C++14 standard: N3936 changes the wording:

    A constant expression is either a glvalue core constant expression whose value refers to an object with static storage duration or to a function, or a prvalue core constant expression whose value is an object where, for that object and its subobjects:

    • each non-static data member of reference type refers to an object with static storage duration or to a function, and
    • if the object or subobject is of pointer type, it contains the address of an object with static storage duration, the address past the end of such an object (5.7), the address of a function, or a null pointer value.

    So changing the declaration of x like so would work:

    constexpr static int x{20};
    

提交回复
热议问题