内部类的奇怪constexpr行为

gd1*_*gd1 10 c++ constexpr c++11

任何人都可以试着解释一下吗?

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 
};
Run Code Online (Sandbox Code Playgroud)

Raf*_*zuk 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 
};
Run Code Online (Sandbox Code Playgroud)

实体cyz1cyz2在内联声明之前被解析Z::noElems(),所以定义

static constexpr size_t noElems() { return C+1; };
Run Code Online (Sandbox Code Playgroud)

在声明时不可用

C<Z> cyz2;
Run Code Online (Sandbox Code Playgroud)