我有以下代码,例如 dec_proxy 尝试反转增量运算符对在复杂函数调用 foo 中执行的类型的影响 - 顺便说一句,我无法更改其接口。
#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 的各种类型,我目前需要创建一个专门的 dec_proxy 实例——这似乎是一种非常混乱和有限的方法。
我的问题是:将这些短暂的临时变量作为非常量引用参数传递的正确方法是什么?