下面的代码将用GCC 5.2编译,而不是用Visual 2015编译。
template <typename Derived>
struct CRTP {
static constexpr int num = Derived::value + 1;
};
struct A : CRTP<A> {
static constexpr int value = 5;
};它抱怨A没有一个名为value的成员。如何修复代码,使其在两个编译器上编译?还是完全不合法?
发布于 2016-03-02 17:43:34
试着让它成为一个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;
}看它的实况here
发布于 2016-03-02 17:53:08
问题在于:
template <typename Derived>
struct CRTP {
static constexpr int num = Derived::value + 1;
↑↑↑↑↑↑↑↑↑
};在CRTP<A>实例化时,A还不是一个完整的类,因此您实际上无法访问它的静态成员。
解决方法之一是将num作为单独的模板参数传递:
template <typename Derived, int N>
struct CRTP {
static constexpr int num = N;
};
struct A : CRTP<A, 5> {
};https://stackoverflow.com/questions/35753956
复制相似问题