声明对引用类型的引用时发生gcc错误

Cal*_*han 1 c++ compiler-errors cray gcc4.8

在OpenCV库中有一个

typedef const _InputArray& InputArray;
Run Code Online (Sandbox Code Playgroud)

在我们的代码中,我们有以下函数定义:

void wimshow(const String& winName, InputArray &img) {
Run Code Online (Sandbox Code Playgroud)

编译时会发生以下错误:

error: cannot declare reference to 'cv::InputArray {aka const class cv::_InputArray&}' void wimshow(const String& winName, InputArray &img) {

奇怪的是,只有在Cray环境中使用GCC 4.8.1才会出现此错误.在具有GCC 4.8.1的普通Linux环境中进行编译可以正常工作.
乍一看,我会说对引用类型的引用无论如何都不是很有意义,但我很好奇什么可能导致不同的编译器行为!?

Lig*_*ica 5

这似乎是C++ 03/C++ 11的不同之处.

在C++ 11中,额外的&(和const偶然的)应该被忽略:

[C++11: 8.3.2/6]: 如果typedef(7.1.3),类型模板参数(14.3.1)或decltype-specifier(7.1.6.2)表示作为类型TR引用的类型T,则尝试创建类型"左值引用" to cv TR "创建类型"左值引用T",而尝试创建类型"rvalue引用cv TR "创建类型TR.

[例如:

int i;
typedef int& LRI;
typedef int&& RRI;
LRI& r1 = i;           // r1 has the type int&
const LRI& r2 = i;     // r2 has the type int&
const LRI&& r3 = i;    // r3 has the type int&
RRI& r4 = i;           // r4 has the type int&
RRI&& r5 = 5;          // r5 has the type int&&
decltype(r2)& r6 = i;  // r6 has the type int&
decltype(r2)&& r7 = i; // r7 has the type int&
Run Code Online (Sandbox Code Playgroud)

- 末端的例子]

这里的相关例子是r1; 虽然typedef int& LRI不完全像你的typedef,但这个例子是等价的,因为以下段落已经放弃了你的const:

[C++11: 8.3.2/1]: [..]除非通过使用typedef(7.1.3)或模板类型参数(14.3)引入cv限定符,否则Cv限定引用的格式不正确,在这种情况下,cv限定符将被忽略.[..]

但是,[C++11: 8.3.2/6]C++ 03中不存在措辞!实际上,我们可以使用以下示例程序比较两种语言之间的行为:

struct T1 {};

typedef T1& T2;

int main()
{
    T1 x;
    T2& t = x;
}
Run Code Online (Sandbox Code Playgroud)

(忽略有关未使用变量的警告)

因此,请检查每个平台上的编译标记,以确保您在两个平台上使用相同的语言.可能是Cray上的默认值是C++ 03,但是你平台上的默认值是C++ 11.使用-std=c++03/ -std=c++11flag来声明显式使用哪个.