这个问题源于一个误解。要清除它:
函子是对象而不是函数
尝试将函数指针或 lambda 分配给对象没有任何意义。所以这是无法做到的:map<int, string> bar([](const int& lhs, const int& rhs){ return lhs > rhs; });定义map带函数指针或 lambda 的方法是使用问题中的模板参数:map<int, string, function<bool(const int&, const int&)>>
问题中两个构思不当的选项之间的中间是另一个误解:map<int, string, [](const int& lhs, const int& rhs){ return lhs > rhs; }>不起作用,因为比较器模板参数是成员的类型map,而不是初始化值。因此,map使用函数指针或 lambda 比较器必须始终将该值传递给map构造函数:map<int, string, function<bool(const int&, const int&)>> bar([](const int& lhs, const int& rhs){ return lhs > rhs; })否则function<bool(const int&, const int&)>()将用于map.
现在这可能已经很清楚了,但是由于函子是对象,因此您不能传递不相关的对象是完全不同类型对象的构造值。打电话map<int, string> foo(greater<int>())就像打电话一样less<int> foo = greater<int>。唯一可接受map的比较器模板参数是仿函数的编译器构造函数参数是可以转换为模板参数中仿函数类型的对象的东西:map<int, string, greater<int>> foo(greater<int>{})这显然是不必要的,因为如果没有提供参数并且greater<int>默认构造了将导致相同的成员初始化map,因此map<int, string, greater<int>>就足够了。