内部类的奇怪constexpr行为

时间:2014-09-17 09:58:33

标签: c++ c++11 constexpr

有人可以试着解释一下吗?

template<typename T, size_t S = T::noElems()>
struct C
{
};

struct X
{
    enum E { A, B, C };
    static constexpr size_t noElems() { return C+1; };
};

struct K
{
    C<X> cx; // this DOES compile
};

struct Y
{
    struct Z
    {
        enum E { A, B, C };
        static constexpr size_t noElems() { return C+1; };
    };
    C<Z, Z::C+1> cyz; // this DOES compile

    C<Z> cyz; // <--- this does NOT compile 
};

1 个答案:

答案 0 :(得分:5)

声明结构

struct Y
{
    struct Z
    {
        enum E { A, B, C };
        static constexpr size_t noElems() { return C+1; };
    };
    C<Z, Z::C+1> cyz1; // this DOES compile

    C<Z> cyz2; // <--- this does NOT compile 
};

实体cyz1cyz2在内联声明Z::noElems()之前进行解析,因此

的定义
static constexpr size_t noElems() { return C+1; };
在宣布

不可用

C<Z> cyz2;