根据政策,您不应该在两个不同的std 类型之间使用运算符重载它们。可能是未定义的行为:标准不明确。
如果您想在 std 容器上使用运算符语法,我建议使用命名运算符。它也更清楚,因为向量上的运算符可以是容器运算符或元素运算符,这就是默认情况下缺少它们的原因。 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> 与上述代码一起使用。