CRTP编译错误

CRTP compiling error

以下将使用 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;
};

它抱怨 A 没有名为 value 的成员。 如何修复代码以便它在两个编译器上编译?还是完全违法?

尝试将其改为 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

问题出在这里:

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

在实例化 CRTP<A> 时,A 还不是一个完整的 class,因此您实际上无法访问它的静态成员。

一种解决方法是将 num 作为单独的模板参数传入:

template <typename Derived, int N>
struct CRTP {
    static constexpr int num = N;
};

struct A : CRTP<A, 5> {

};