【发布时间】:2014-09-03 02:45:30
【问题描述】:
我知道“转发”在 C++11 中是一个不相关的概念(如“完美转发”),但这是我描述问题时想到的第一个词。
我正在覆盖包装类 Proxy 中的 operator=,
template<typename T>
class Proxy
{
public:
enum class State
{
NEVER_SET = 0,
SET
};
operator const T& () const
{
if ( _state != State::SET )
{
throw std::domain_error{ "using unset data" };
}
return _data;
}
Proxy<T>& operator=(const T& val)
{
_data = val;
_state = State::SET;
return (*this);
}
private:
T _data;
State _state = State::NEVER_SET;
};
但发现自己也需要补充:
Proxy<T>& operator+=(const T& val)
{
_data = (*this) + val;
_state = State::SET;
return (*this);
}
Proxy<T>& operator-=(const T& val)
{
_data = (*this) - val;
_state = State::SET;
return (*this);
}
Proxy<T>& operator*=(const T& val)
{
_data = (*this) * val;
_state = State::SET;
return (*this);
}
Proxy<T>& operator/=(const T& val)
{
_data = (*this) / val;
_state = State::SET;
return (*this);
}
// ...and so on.
是否有“转发”所有赋值运算符(+=、-=、*=、/=、%=、>>=、<<=、|=、&= , ^=) 这样我就不必定义它们了?也就是制作方法
Proxy<double> x = 7;
Proxy<double> y = 43;
x += y;
自动“解开”到
Proxy<double> x = 7;
Proxy<double> y = 43;
x = x + y; // cast operator converts x and y to double, then direct assigns sum,
// therefore no += needing definition in Proxy<T>
【问题讨论】:
-
你可以用
boost::operators做相反的事情(即定义+=并让+自动生成)。 -
嗯,但目前看来我不需要生成
+,因为转换操作为我方便地定义了+,其中基础数据类型T具有适当的运算符。我希望有一种技术可以让我只定义直接赋值运算符。 -
@AndrewCheong 为什么不把
operator+=的body 变成*this = *this + val;,达到将x += y解开为x = x + y的目的。 -
(我认为这不是一个好主意,因为它比在不参考
operator=的情况下实现operator+=更多操作,但这是您要求的!)
标签: c++ templates c++11 operator-overloading wrapper