CRTP编译错误

pre*_*eys 4 c++ templates crtp constexpr c++11

以下内容将使用GCC 5.2进行编译,但不能使用Visual Studio 2015进行编译.

template <typename Derived>
struct CRTP {
    static constexpr int num = Derived::value + 1;
};

struct A : CRTP<A> {
    static constexpr int value = 5;
};
Run Code Online (Sandbox Code Playgroud)

它抱怨说A没有名字的成员value.如何修复代码以便在两个编译器上编译?或者完全是非法的?

Sto*_*ica 6

尝试使它成为constexpr功能.您现在设置它的方式是尝试访问不完整的类型.
由于模板化成员函数仅在首次使用时初始化,因此类型A将由该点完全定义.

#include <iostream>

template <typename Derived>
struct CRTP {
    static constexpr int num() { return  Derived::value + 1; }
};

struct A : CRTP<A> {
    static constexpr int value = 5;
};

int main()
{
    std::cout << A::num();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这里看到它