【发布时间】:2019-06-24 00:59:22
【问题描述】:
当我为我的项目编写代码时,我发现了一个非常奇怪的情况,我的 C++11 代码无法在 GCC 7.3 和 之间交叉编译>MSVC 2015。案子基本是这样的:
// .H file
template <typename X>
struct Outer {
X x = {};
template <typename Y>
struct Inner {
Y y = {};
Inner& operator++();
};
};
// .INL file
template <typename X>
template <typename Y>
inline Outer<X>::Inner<Y>&
Outer<X>::Inner<Y>::operator++()
{
++y;
return *this;
}
// .CPP file
#include <iostream>
int main()
{
Outer<int>::Inner<int> a;
++a;
std::cout << a.y << std::endl;
return 0;
}
GCC 不会抱怨上面的代码。但 MSVC 会,错误是:
warning C4346: 'Inner': dependent name is not a type note: prefix with
'typename' to indicate a type error C2061: syntax error: identifier
'Inner' error C2143: syntax error: missing ';' before '{' error C2447:
'{': missing function header (old-style formal list?)
根据 MSVC 编译器本身的建议,在返回类型上写入 typename 关键字将解决此问题:
template <typename X>
template <typename Y>
inline typename Outer<X>::Inner<Y>&
Outer<X>::Inner<Y>::operator++()
{
++y;
return *this;
}
但是现在,令人惊讶的是,GCC 不再编译了,它的错误是:
error: non-template 'Inner' used as template
inline typename Outer<X>::Inner<Y>&
^~~~~ note: use 'Outer<X>::template Inner' to indicate that it is a template error: expected
unqualified-id at end of input
再次,按照编译器本身的建议,我尝试将关键字 template 添加到返回类型,这将解决 GCC 的问题:
template <typename X>
template <typename Y>
inline typename Outer<X>::template Inner<Y>&
Outer<X>::Inner<Y>::operator++()
{
++y;
return *this;
}
但是这个修复现在将再次破坏 MSVC 构建,并且来自编译器的错误是:
error C2244: 'Outer<X>::Inner<Y>::operator ++': unable to match
function definition to an existing declaration note: see declaration
of 'Outer<X>::Inner<Y>::operator ++' note: definition note:
'Outer<X>::Inner<Y> &Outer<X>::Inner<Y>::operator ++(void)' note:
existing declarations note: 'Outer<X>::Inner<Y>
&Outer<X>::Inner<Y>::operator ++(void)'
这一次,我只是停下来,因为编译器错误消息没有帮助,因为报告的定义和声明之间的不匹配不存在:编译器本身给出的签名完全匹配。
此时,不知道有什么更好的解决方案,我决定只在 .H 文件的内部类范围内定义函数,这对 GCC 和 MSVC 都有效。但仍然存在一些问题:谁是对的? GCC 还是 MSVC?还是在这种情况下 C++ 标准过于模棱两可?
【问题讨论】:
-
使用条件编译。
-
@jxh 不会回答“谁是对的?”问题我相信
-
@rustyx: 那么需要语言律师标签。
标签: c++ c++11 gcc visual-c++ language-lawyer