参考崩溃? [英] Reference collapsing?

查看:192
本文介绍了参考崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过尝试解决此问题,有些事让我很奇怪。考虑下面的代码:

By trying to solve this problem, something made me wonder. Consider the following code:

template <typename T>
struct foo 
{
    foo(T const& x) : data(x) {}
    T data;
};

看起来我可以构造一个类型 foo< T const& > 没有错误,假设 T const& const& 被理解为 T const&

It seems that I can construct an object of type foo<T const&> without error, the hypothetical T const& const& being understood as T const&.

调用参考折叠,但我从来没听说过这个术语(见链接问题中的注释)。

It seems also that this is called reference collapsing, but I never heard this term before (see comments in the linked question).

这是广泛的吗?这是标准吗?

Is this widespread ? Is this standard ?

推荐答案

在C ++ 03中,执行以下操作是不合法的

In C++03, it was not legal to do the following

typedef int &ref;
ref &r = ...; // reference to reference!

这经常导致人们编译真正严格或更老的C ++ 03编译器(GCC4.1以及Comeau 8/4/03不喜欢上述),因为标准函数对象绑定器不会处理引用引用情况,并偶尔创建这种非法类型。

This frequently causes problems for people compiling with really strict or older C++03 compilers (GCC4.1 as well as Comeau 8/4/03 do not like the above) because the Standard function object binders do not take care of the "reference to reference" situation, and occasionally create such illegal types.

在C ++ 0x中,这被称为参考折叠,是的。大多数当前的C ++ 03编译器做这个(即 T& 其中 T 表示参考类型 T ),通过追溯应用规则。 boost.call_traits 库可轻松声明此类函数参数,因此,即参考情况不发生。

In C++0x this is called "reference collapsing", yes. Most current C++03 compilers do that (i.e a T& where T denotes a reference type is T again), by retroactively applying the rule. The boost.call_traits library makes it easy to declare such function parameters though, so that the "reference to reference" situation does not occur.

请注意, const 没有任何效果。默认忽略应用于引用类型的 const 。因此,即使编译器支持引用折叠,以下是不合法的

Please note that the const there does not have any effect. A const applied on a reference type is silently ignored. So even if the compiler supports reference collapsing, the following is not legal

int const x = 0;

// illegal: trying to bind "int&" to "int const"!
ref const& r = x; 

这篇关于参考崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆