C++ CRTP和静态成员初始化
当我编译以下代码时C++ CRTP和静态成员初始化,c++,C++,当我编译以下代码时 template <typename Derived> struct Bar { static inline constexpr int x = Derived::value; }; struct Foo : Bar<Foo> { static inline constexpr int value = 101; }; 模板结构栏 { 静态内联constexpr int x=派生::值; }; 结构Foo:Bar { 静态内联co
template <typename Derived> struct Bar
{
static inline constexpr int x = Derived::value;
};
struct Foo : Bar<Foo>
{
static inline constexpr int value = 101;
};
模板结构栏
{
静态内联constexpr int x=派生::值;
};
结构Foo:Bar
{
静态内联constexpr int值=101;
};
使用VS 2019 16.6时出现编译错误
Source.cpp(5,47): error C2039: 'value': is not a member of 'Foo'
Source.cpp(8): message : see declaration of 'Foo'
Source.cpp(9): message : see reference to class template instantiation 'Bar<Foo>' being compiled
Source.cpp(5,1): error C2065: 'value': undeclared identifier
Source.cpp(5,1): error C2131: expression did not evaluate to a constant
Source.cpp(5,1): message : a non-constant (sub-)expression was encountered
Source.cpp(5,47):错误C2039:'value':不是'Foo'的成员
cpp(8):信息:见“Foo”的声明
cpp(9):消息:请参阅对正在编译的类模板实例化“Bar”的引用
Source.cpp(5,1):错误C2065:“值”:未声明的标识符
Source.cpp(5,1):错误C2131:表达式的计算结果不是常数
Source.cpp(5,1):消息:遇到一个非常量(子)表达式
那么,从CRTP派生类初始化静态是非法的还是编译器错了?
我当然发现错误“'value':不是'Foo'的成员”很奇怪,因为value显然是一个成员。它是用gcc和clang编译的,我不确定这怎么可能工作,因为在实例化
Bar
时,Foo
是不完整的,并且还没有成员值
。嗯。。。在@Nicolabolas的评论之后,我不太确定这是MSVC的bug。其他涉及在CRTP中使用不完整类型的情况也会在gcc和clang中失败:@NicolBolas所以Bar::x=Foo::value
在你请求Bar::x
之前都不重要,只要Foo
和Foo::value
在那时存在,你就没事了。阿米尔,你赢了我,但我也已经投降了!我在两个VS社区问题中添加了评论,并将它们链接起来。