【发布时间】:2015-05-15 17:39:48
【问题描述】:
这个问题的灵感来自Issue with std::reference_wrapper。例如,假设operator< 代表std::vector。它被定义为函数模板
template< class T, class Alloc >
bool operator<( const vector<T,Alloc>& lhs,
const vector<T,Alloc>& rhs );
因此,函数参数到相应函数参数类型的隐式转换被拒绝(主要是因为它的模板性质)。这大大降低了std::reference_wrapper 的实用性和便利性。例如,您不能在 std::vector<std::reference_wrapper<std::vector<int>>> 上使用 std::sort。
另一方面,只有将operator< 定义为像这样的非模板 Koenig 运算符,才能解决所有问题
template <...>
class vector ... {
friend bool operator<(const vector& a, const vector& b) {...}
};
我想知道为什么标准库采用了前一种方法而不是这种方法?
【问题讨论】:
-
好吧,在
operator <标准化的时候,reference_wrapper不存在,AFAIK。 -
关于措辞:没有 Koenig 运算符。相反,有一些函数可以通过 ADL/Koenig 查找找到。
-
这不是问题,但我认为在发明 SGI STL 的时候,它仍然与优化器相关。 -- 还要注意这个函数不需要是朋友(不需要特权访问),所以也许它被认为是一个更干净的解决方案。
-
也许更好的方式来允许这个 btw 是添加包装操作符到
std::reference_wrapper,就像它的operator()一样。 -
这里有一个问题:假设您想为 std::vector
重载 operator
标签: c++ c++11 implicit-conversion standard-library reference-wrapper