gpt4 book ai didi

c++ - CRTP编译错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:37 24 4
gpt4 key购买 nike

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

关于c++ - CRTP编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35753956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com