作为一项政策,您不应将两个不同的std
类型与它们之间的运算符重载。这可能是未定义的行为:标准不明确。
如果你想在std
容器上使用操作符语法,我会推荐命名操作符。还有一点更加清楚,因为vector上的操作符可能是容器操作符或元素操作符,这就是缺省默认情况下缺失的原因。 v +append= v2;
显然是附加。 (创建静态追加对象,和过载其LHS和rhs运营你的载体,和在该中间步骤使用表达式模板)
// mini named operator library. Only supports + for now:
template<class Kind>
struct named_operator {};
template<class OP, class LHS> struct plus_ {
LHS lhs;
template<class RHS>
decltype(auto) operator=(RHS&&rhs)&&{
return plus_assign(std::forward<LHS>(lhs), OP{}, std::forward<RHS>(rhs));
}
template<class RHS>
decltype(auto) operator+(RHS&&rhs)&&{
return plus(std::forward<LHS>(lhs), OP{}, std::forward<RHS>(rhs));
}
};
template<class Tag, class LHS>
plus_<Tag,LHS> operator+(LHS&& lhs, named_operator<Tag>) {
return {std::forward<LHS>(lhs)};
}
// creating a named operator:
static struct append_tag:named_operator<append_tag> {} append;
// helper function, finds size of containers and arrays:
template<class T,std::size_t N>
constexpr std::size_t size(T(&)[N]) { return N; }
template<class C>
constexpr auto size(C&& c)->decltype(c.size()) { return c.size(); }
// implement the vector +append= range:
template<class T, class A, class RHS>
std::vector<T,A>& plus_assign(std::vector<T,A>&lhs, append_tag, RHS&& rhs) {
auto rhs_size = size(rhs);
lhs.reserve(lhs.size()+rhs_size);
using std::begin; using std::end;
copy_n(begin(rhs), rhs_size, back_inserter(lhs));
return lhs;
}
// implement container +append+ range:
template<class LHS, class RHS>
LHS plus(LHS lhs, append_tag, RHS&& rhs) {
using std::begin; using std::end; using std::back_inserter;
copy_n(begin(rhs), size(rhs), back_inserter(lhs));
return std::move(lhs);
}
live example
注意std::vector<int> +append= std::list<int> +append+ std::array<double, 3>
作品与上面的代码。
'的std ::矢量&运算+ =(标准::矢量&LHS,常量性病::矢量&RHS)'适用于自赋值为好。 –
101010
2014-10-18 19:29:16
@ 40two不,它不连接rhs。 – user4157389 2014-10-18 19:31:18
真的吗? [LIVE DEMO](http://coliru.stacked-crooked.com/a/e1b7f483ae0e5723) – 101010 2014-10-18 19:32:24