我知道“转发”在C++11中是一个不相关的概念(就像在“完美转发”中一样),但是对于我来说,这是描述问题的第一个词。
我在包装类operator=中重写Proxy,
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>发布于 2014-09-03 03:09:01
您可以使用CRTP,但是如果您的目标是在代理类中只有一个显式的=,则需要提供对其他操作符已经可用的类型的一些访问。换句话说,如果定义了如何分配而不是如何添加,就不能说是a1 = a2 + a3。我在下面通过期望一个get()函数来解决这个问题,该函数公开了一些可以操作的状态。显式定义要典型得多(而且可能是实用的),例如+=然后用它定义+ .
#include <iostream>
template <typename T>
struct Implied_Ops
{
T operator+(const T& rhs) const
{
return rhs.get() + static_cast<const T*>(this)->get();
}
T& operator+=(const T& rhs)
{
return static_cast<T&>(*this) = operator+(rhs);
}
};
struct X : Implied_Ops<X>
{
X(int n) : n_(n) { }
X& operator=(const X& rhs) { n_ = rhs.n_; return *this; }
int get() const { return n_; }
int n_;
};
int main()
{
X x { 10 };
X x2 = x + x;
X x3 = x + x2;
std::cout << x.n_ << ' ' << x2.n_ << ' ' << x3.n_ << '\n';
}另一种不容忽视的方法是宏.
发布于 2014-09-03 03:06:26
是的与CRTP。
template<class D>
struct plus_equals {
template<class Rhs>
D& operator+=(Rhs&& rhs){
D*self=static_cast<D*>(this);
self->_data = (*self)+std::forward<Rhs>(rhs);
self->_state= State::SET;
return *self;
}
};然后公开地从Foo继承您的类plus_equals<Foo>。
当然,您需要为每个操作符编写样板,所以对一种类型没有多大帮助。
https://stackoverflow.com/questions/25635433
复制相似问题