Contents

C++ Constexpr Static Instances

Contents

下面这个代码是无法编译通过的

class A {
public:
    A(val) : val{val} {}
    
    static constexpr A a1{0};
    
private:
    int val;
};

不过稍加修改就可以了,参考这里

7.1.5p9 The constexpr specifier [dcl.constexpr] (n3337)

A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized.

class A {
public:
    A(val) : val{val} {}

    static const A a1;
    
private:
    int val;
};

constexpr A A::a1{0};