簡體   English   中英

constexpr成員變量,嵌套類的問題

[英]Trouble with constexpr member variables, nested classes

我正在嘗試編寫一個具有多個靜態constexpr值的類; 這似乎是不允許的,因為constexpr聲明需要類聲明中不可用的類的定義。 我的第一次嘗試的MCV看起來像這樣:

struct A {
    constexpr A(float x) : _x(x) {}
    float _x;

    static constexpr A y = A(1.f);
    // gcc-5.1:
    // error: invalid use of incomplete type 'struct A'
    // static constexpr A y = A(1.f);
    //                             ^
    // msvc-14:
    // error C2027: use of undefined type 'A'
    // note: see declaration of 'A'
    // note: see declaration of 'A'
    // error C2079: 'public: static A const A::y' uses undefined struct 'A'
};

我的下一次嘗試是聲明一個'常量'類(隱式轉換為數據類,此處未顯示)。 這似乎工作正常:

struct B_constant {
    constexpr B_constant(float x) : _x(x) {}
    float _x;
};

struct B {
    static constexpr B_constant y = B_constant(1.f);
};

但是,這是一個有點難看,所以我想我會嘗試讓恆類嵌套類的數據類的,但是這並不工作:

struct C {
    struct C_constant {
        constexpr C_constant(float x) : _x(x) {}
        float _x;
    };

    static constexpr C_constant y = C_constant(1.f);
    // gcc-5.1:
    // error: 'constexpr C::C_constant::C_constant(float)' called in a constant expression
    // static constexpr C_constant y = C_constant(1.f);
    //                                               ^
    // msvc-14:
    // error C2131: expression did not evaluate to a constant
    // note: failure was caused by call of undefined function or one not declared 'constexpr'
    // note: see usage of 'C::C_constant::C_constant'
};

我注意到失敗類似於聲明constexpr構造函數時的錯誤,但是在數據類中使用它之后定義它:

struct D_constant {
    constexpr D_constant(float x);
    float _x;
};

struct D {
    static constexpr D_constant y = D_constant(1.f);
    // gcc-5.1:
    // error: 'constexpr D_constant::D_constant(float)' used before its definition
    // static constexpr D_constant y = D_constant(1.f);  
    //                                               ^
    // msvc-14:
    // error C2131: expression did not evaluate to a constant
    // note: failure was caused by call of undefined function or one not declared 'constexpr'
    // note: see usage of 'D::D_constant::D_constant'
};

constexpr D_constant::D_constant(float x) : _x(x) {}

任何人都可以了解第三個例子的情況嗎? 盡管嵌套類聲明已完成,但似乎編譯器無法在嵌套類中找到constexpr構造函數的定義。 有誰知道一個更好的方法來完成我想要做的事情?

如前所述這里

在類說明符的結束時,類被視為完全定義的對象類型(或完整類型)。 [...]否則在其自己的類成員規范中被視為不完整。

其中[...]是一個沒有提到嵌套類的異常列表。

定義了成員規范

類定義中的成員規范聲明了該類的完整成員集; 其他任何成員都無法添加。 類的成員是數據成員,成員函數,嵌套類型,枚舉器以及其成員模板和特化。 [...]

因此,嵌套類被認為是類規范的一部分,並且在您具有完整類型(即在結束時} ,不能引用它,將所提到的異常置之不理。
數據成員也是成員規范的一部分,在聲明此類成員時,必須將該類視為不完整。
請注意,通過使用名稱C_constant您實際上使用的是限定名C::C_constant ,它是C定義的一部分。 您可以使用C中較短的標識符來引用它並不會改變其性質。

有誰知道一個更好的方法來完成我想要做的事情?

對你來說, A::y是一個對象而不是函數或函子可能並不重要。 如果沒有,你可以解決障礙,如:

struct A {
    constexpr A(float x) : _x(x) {}
    float _x;

    static constexpr A y() {
        return A(1.f);
    }
};

constexpr A y = A::y();
static_assert(y._x == 1.f,"");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM