使用以下代码可以清楚地解决该问题:
#include <functional>
#include <iostream>
#include <vector>
int main() {
//std::vector<int> a, b;
int a = 0, b = 0;
auto refa = std::ref(a);
auto refb = std::ref(b);
std::cout << (refa < refb) << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用注释std::vector<int> a, b;而不是int a = 0, b = 0;,则代码不会在GCC 5.1,clang 3.6或MSVC'13中的任何一个上编译.在我看来,std::reference_wrapper<std::vector<int>>可以隐式转换std::vector<int>&为LessThanComparable,因此它应该是LessThanComparable本身.有人可以向我解释一下吗?
c++ language-lawyer implicit-conversion c++11 reference-wrapper
这个问题的灵感来自于std :: reference_wrapper的问题.让我们说,例如,operator<对于std::vector.它被定义为函数模板
template< class T, class Alloc >
bool operator<( const vector<T,Alloc>& lhs,
const vector<T,Alloc>& rhs );
Run Code Online (Sandbox Code Playgroud)
因此,拒绝将函数参数隐式转换为相应函数参数的类型(主要是因为其模板性质).这大大降低了它的实用性和便利性std::reference_wrapper.例如,您不能使用std::sort的std::vector<std::reference_wrapper<std::vector<int>>>.
另一方面,只有当operator<定义为非模板Koenig运算符时,才能解决所有问题
template <...>
class vector ... {
friend bool operator<(const vector& a, const vector& b) {...}
};
Run Code Online (Sandbox Code Playgroud)
我想知道为什么标准库采用了前一种方法而不是这种方法?
c++ standard-library implicit-conversion c++11 reference-wrapper