CRTP编译错误 [英] CRTP compiling error
本文介绍了CRTP编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下将使用GCC 5.2进行编译,但不能与Visual Studio 2015一起编译。
The following will compile with GCC 5.2 but not with 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
。
如何修复代码,使其编译在两个编译器?
It complains that A
does not have a member named value
.
How to fix the code so that it compiles on both compilers? Or is it illegal altogether?
推荐答案
尝试使用constexpr函数。
由于模板成员函数只在首次使用时初始化,请键入 A
将由该点完全定义。
Try making it a constexpr function instead. The way you have it setup now attempts to access an incomplete type.
Since a templated member function will only be initialized upon first being used, type A
will be fully defined by that point.
#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;
}
查看现场这里
这篇关于CRTP编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文