c ++ - 是否有一种方法在将值分配给引用时自动转换值? [英] c++ - Is there a way to auto-cast values when assigning them to references`?
问题描述
class我想知道是否有一些C ++自动播放值要分配给引用的方法。 X {
public:
X(int x){
}
};
int main(){
X x = 5; // works
X& y = 6; //不工作
X& z =(X)7; // works
return 0;
}
正如你所看到的,它之前。有没有什么我可以添加在类X的定义,使这个工作没有铸造,所以非工作线路将工作?
基本上我想例如这样的函数:
void doSomething(X& x){
// .. 。
}
之后可以这样调用:
doSomething(7);
是否有可能?
对非 - const
的值引用只能绑定到左值。 6
是一个prvalue,因此它不能绑定到 y
。您在此行中的操作:
X& z =(X)7;
基本上等同于:
X& z = X(7);
在右侧,它创建一个 X
,然后将其绑定到一个左值引用。在C ++中,这是非法的 - 临时值是右值。你的编译器可能允许这样做是一个(不是很聪明)的文档扩展。
避免编写这种代码。另一方面,这是合法的:
X const& z = 6;
临时绑定到 z
将被延长以匹配 z
引用本身(12.2 / 5)的生命周期。所以你应该这样写你的函数:
void doSomething(X const& x)
// ^^^ ^^
{
// ...
}
对 const
的引用可以绑定到右值(包括临时值)。因此,以下调用是合法的:
doSomething(7)
pre>
并且通过提供
7 $来构造
X
c $ c>作为构造函数的参数,然后将函数参数x
绑定到该临时。I'm wondering if there is some way that C++ autocasts values that I want to assign to a reference.
class X{ public: X(int x){ } }; int main(){ X x = 5; //works X& y = 6; //doesn't work X& z = (X)7; //works return 0; }
As you can see, assigning 6 to the reference y does not work without casting it before. Is there something I can add in the definition of the class X to make this work without the casting, so that the non-working line would work?
Basically I want to achieve that, for example a function like this:
void doSomething(X& x){ //... }
Could be called like this after that:
doSomething(7);
Is it possible?
解决方案lvalue references to non-
const
can only bind to lvalues.6
is a prvalue, so it cannot bind toy
. What you are doing in this line:X& z = (X)7;
Is basically equivalent to this:
X& z = X(7);
On the right side, it creates a temporary of type
X
, and then binds it to an lvalue reference. In C++, this is illegal - temporaries are rvalues. Your compiler probably allows doing so as a (not very clever) documented extension.Avoid writing that kind of code. This, on the other hand, is legal:
X const& z = 6;
And the lifetime of the temporary bound to
z
will be prolonged to match the lifetime of thez
reference itself (12.2/5). So you should write your function this way:void doSomething(X const& x) // ^^^^^ { //... }
lvalue references to
const
can bind to rvalues (including temporaries). Therefore, the following call would be legal:doSomething(7)
And it would construct a temporary of type
X
by providing7
as the constructor's argument, then binding the function parameterx
to that temporary.这篇关于c ++ - 是否有一种方法在将值分配给引用时自动转换值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!