我试图为容器定义一个通用运算符,如下所示:
#include <algorithm>
#include <functional>
namespace test {
template<template <typename...> class _Container,
typename _Type, typename... _Args>
_Container<_Type,_Args...>
operator+(const _Container<_Type,_Args...>& c1,
const _Container<_Type,_Args...>& c2)
{
typedef _Container<_Type,_Args...> container_type;
assert(c1.size() == c2.size());
container_type result;
std::transform(c1.begin(), c1.end(), c2.begin(),
std::back_inserter(result), std::plus<_Type>());
return result;
}
} // test namespace
但是,GCC 4.9.2不会尝试作为以下测试代码的候选者:
typedef std::vector<int> vector;
vector v1, v2;
vector result = v1 + v2;
我也尝试了上面没有模板的参数包。结果相同。
但是,没有名称空间声明,它可以正常工作。
我做错了什么?由std
命名空间中的STL定义的类似运算符作为候选者进行测试。
错误信息只是:
/tmp/file.cc: In function ‘int main()’:
/tmp/file.cc:28:22: error: no match for ‘operator+’ (operand types are ‘vector {aka std::vector<int>}’ and ‘vector {aka std::vector<int>}’)
答案 0 :(得分:2)
噢,哦......我试图为容器定义通用运算符
忽略您将遇到的ADL问题,也存在语义问题。
例如,考虑:
vector<int> a { 1, 2, 3 };
vector<int> b { 4, 5, 6 };
auto c = a + b; // this won't compile, it's for illustration.
问题:手术应该做什么?
有些人可能认为应该对此进行建模:
auto c = concatenate(a, b);
// c == { 1, 2, 3, 4, 5, 6 }
其他人可能会认为它应该像你建议的那样:
auto c = add_elements(a, b);
// c == { 5, 7, 9 }
谁没事?
答案是它取决于矢量的使用环境。矢量是原始类型。它不包含有关用例的信息。根本没有足够的信息可以做出明智的选择。
将矢量包装成自定义类型允许您提供上下文信息并正确描述操作符的操作。
当然,您需要为类型明确定义算术运算符。
总结:
标准库没有为容器定义算术运算符。出于同样的原因,你也不应该。
作为一个分离注释,即使是变换解释也不是微不足道的。如果向量大小不同会发生什么?