【发布时间】:2014-01-20 01:22:00
【问题描述】:
关于为is_densevector 类实现operator-,我想要:
g = -v; 调用第一个版本的运算符(v 的克隆将是负数),并且:
g = -std::move(v);
g = -(v + v);
g = -std::vector<double>({1,2,3});
调用运算符的第二个版本(向量本身将是负数——出于性能考虑)。
诀窍是!std::is_reference<C>::value,但我不确定这是否正确。似乎它正在工作。
//! Return the negative of vector \p v.
template<typename C>
typename std::enable_if<is_densevector<C>::value, C>::type
operator-(const C &v) { return ....; }
//! Return the negative of vector \p v.
template<typename C>
typename std::enable_if<!std::is_reference<C>::value && is_densevector<C>::value, C>::type
&&operator-(C &&v) { ....; return std::move(v); }
【问题讨论】:
-
ideone.com/4suqp4 像这样??不确定
is_densevector做了什么 -
不完全是。黑盒化的
is_densevector<C>::value对C=std::vector<Integral>和C=std::array<Integral,Size>等都适用。同样在您的示例中,您没有使用“魔术”C&&v作为函数参数。 -
你是什么意思我没有使用移动'魔法'作为函数参数?它在运算符的第二个声明中使用移动语义。我发布的签名与您拥有的签名之间的唯一区别是您的签名是模板化的。再次检查上面的链接,发现它使用了移动语义,因为分配的向量是临时的。给操作符添加打印语句,查看:ideone.com/4cOh1i
标签: c++ templates c++11 operator-overloading rvalue-reference