问题描述
尝试使用lambda覆盖map::compare
函数,看来以下解决方案有效.
Trying to override map::compare
function using lambda, it seems that the following solution works.
auto cmp = [](const int&a, const int& b) { return a < b; };
std::map<int, int, decltype(cmp)> myMap(cmp);
但是,我必须先定义cmp
,然后再使用.
我可以不定义"cmp"来做到这一点吗?
But, I had to define cmp
first and use it later.
Can I do this without defining 'cmp'?
推荐答案
否,您不能在未评估的上下文中使用lambda,即示例中的模板参数.因此,您必须在其他地方定义它(使用auto
),然后使用decltype
...,相反,正如已经提到的那样,它是使用常规"函子
No, you can't use lambda in unevaluated context -- i.e. template parameters as in your example.So you must define it somewhere else (using auto
) and then use decltype
... the other way, as it was mentioned already is to use an "ordinal" functors
如果您的问题是关于"如何在定义地图时使用lambda表达式* * ",则可以利用lambda隐式转换为std::function
的方法:
If your question is about "how to use lambda expression *once* when define a map" you can exploit implicit conversion of lambdas to std::function
like this:
#include <iostream>
#include <functional>
#include <map>
int main()
{
auto m = std::map<int, int, std::function<bool(const int&, const int&)>>{
[](const int& a, const int& b)
{
return a < b;
}
};
return 0;
}
您可以为该map
类型引入别名,以减少以后的输入...
you may introduce an alias for that map
type to reduce typing later...
这篇关于直接覆盖map :: compare与lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!