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;
}
在这里观看直播
问题就在这里:
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> {
};
相关文章:
- 用MacOS Mojave编译C++:致命错误:mpi.h:没有这样的文件或目录
- std::is_base_of表示ctor编译错误
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- Qt Cmake 错误编译"GuiSupportQt not found"
- Opengl 精度转换错误编译错误 E0415
- 库将ARM架构错误编译为架构X64
- RT 音频 Mac 错误 g++ 编译错误
- 错误编译Boost.log
- 错误编译QT创建者 / QT窗口小部件示例
- 错误编译MIPS32
- Visual Studio 2013 中的错误(编译和运行代码)
- 链接错误编译qt项目在visual 2010
- 无法用模板错误编译nsgmls
- 奇怪的错误.编译失败
- 如果有人调用c++中的方法,则强制错误(编译时)
- 来自autoconf测试的错误编译命令
- 时间限制超出错误C++编译
- SFML 2.3 和 CodeBlocks 错误编译