在C ++中将临时变量作为非const引用 [英] Passing temporaries as non-const references in C++
问题描述
我有以下代码片段,例如dec_proxy尝试反转增量运算符对复杂函数调用foo中执行的类型的影响 - 其中btw不能更改接口。
I have the following piece of code, as an example dec_proxy attempts to reverse the effects of the increment operator upon the type that is executed in a complex function call foo - which btw I cannot change the interface of.
#include <iostream>
template<typename T>
class dec_proxy
{
public:
dec_proxy(T& t)
:t_(t)
{}
dec_proxy<T>& operator++()
{
--t_;
return *this;
}
private:
T& t_;
};
template<typename T, typename S, typename R>
void foo(T& t, S& s, R& r)
{
++t;
++s;
++r;
}
int main()
{
int i = 0;
double j = 0;
short k = 0;
dec_proxy<int> dp1(i);
dec_proxy<double> dp2(j);
dec_proxy<short> dp3(k);
foo(dp1,dp2,dp3);
//foo(dec_proxy<int>(i), <---- Gives an error
// dec_proxy<double>(j), <---- Gives an error
// dec_proxy<short>(k)); <---- Gives an error
std::cout << "i=" << i << std::endl;
return 0;
}
问题是对于各种类型我想使用dec_proxy I目前需要创建一个专门的dec_proxy实例 - 它似乎是一个非常混乱和有限的方法。
The problem is that for the various types I'd like to use dec_proxy I currently require creating a specialized instance of dec_proxy - it seems like a very messy and limited approach.
我的问题是:将这种短暂临时变量作为非const引用参数传递的正确方法是什么?
My question is: What is the correct way to pass such short-lived temporaries as non-const reference parameters?
推荐答案
采取斯蒂芬的建议,你应该看看如何使非const引用不能绑定到临时对象?,只需添加一个成员函数,返回一个引用 dec_proxy
,例如:
Taking Stephen's advice, you should look at the answer to How come a non-const reference cannot bind to a temporary object? and simply add a member function that returns a reference dec_proxy
, e.g.:
dec_proxy& ref(){return * this; }
并致电 foo
:
foo(
dec_proxy<int>(i).ref(),
dec_proxy<double>(j).ref(),
dec_proxy<short>(k).ref());
我很肯定编译。
这篇关于在C ++中将临时变量作为非const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!