2016-03-02 46 views
0

是否有一个原因,我无法通过比较仿函数的map构造函数参数:地图比较构造函数的参数

map<int, string, greater<int>> foo; 
//map<int, string> foo(greater<int>()); Doesn't work 

或者为什么我不能没有提供我自己的比较式传递一个拉姆达:

map<int, string, function<bool(const int&, const int&)>> bar([](const int& lhs, const int& rhs){ return lhs > rhs; }); 
//map<int, string> bar([](const int& lhs, const int& rhs){ return lhs > rhs; }); Doesn't work 

我想只能声明map<int, string>并用比较器构造它。为什么我不能?

[Live Example]

+0

因为这会涉及一些类型擦除,这不是最佳的? –

+0

可能的重复:[为什么不从构造函数推断模板参数?](http://stackoverflow.com/questions/984394/why-not-infer-template-parameter-from-constructor) – NathanOliver

+0

@PiotrSkotnicki你在说,对于函子的版本?但是'map'没有提供比较构造函数? http://www.cplusplus.com/reference/map/map/map/是不是这到底是什么? –

回答

1

这个问题从一个误解茎。要清除起来:

仿函数对象功能

尝试指派一个函数指针或拉姆达一个对象没有任何意义。因此,这不能做: 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,而不是的初始值。 因此,使用函数指针或lambda比较器的map必须始终将该值传递给构造函数mapmap<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其比较器模板参数是一个函子的唯一可接受的compatator构造函数参数是可以转换为模板参数中函子类型的对象的东西:map<int, string, greater<int>> foo(greater<int>{})这显然是不必要的,因为如果没有提供参数, greater<int>是默认构造的map会导致相同的成员初始化,所以map<int, string, greater<int>>是足够的。

+1

'map > foo(更大())'是函数声明(最令人头痛的解析) –

+0

@PiotrSkotnicki呃,谢谢。很明显,我没有尝试过,因为这没什么意义。我编辑过,并且实际测试了它现在的作用:http://ideone.com/1Ygrze –