如何使用lambda表达式作为模板参数? [英] How to use a lambda expression as a template parameter?

查看:895
本文介绍了如何使用lambda表达式作为模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用lambda表达式作为模板参数?例如。作为初始化std :: set的比较类。

How to use lambda expression as a template parameter? E.g. as a comparison class initializing a std::set.

以下解决方案应该可以工作,因为lambda表达式只创建一个匿名结构,它应该适合作为模板参数。

The following solution should work, as lambda expression merely creates an anonymous struct, which should be appropriate as a template parameter. However, a lot of errors are spawned.

代码示例:

struct A {int x; int y;};
std::set <A, [](const A lhs, const A &rhs) ->bool {
    return lhs.x < rhs.x;
    } > SetOfA;

错误输出(我使用g ++ 4.5.1编译器和--std = c ++ 0x编译标志):

Error output (I am using g++ 4.5.1 compiler and --std=c++0x compilation flag):

error: ‘lhs’ cannot appear in a constant-expression
error: ‘.’ cannot appear in a constant-expression
error: ‘rhs’ cannot appear in a constant-expression
error: ‘.’ cannot appear in a constant-expression
At global scope:
error: template argument 2 is invalid

是GCC中预期的行为还是错误?

Is that the expected behavior or a bug in GCC?

编辑

正如有人指出,我使用lambda表达式不正确,

As someone pointed out, I'm using lambda expressions incorrectly as they return an instance of the anonymous struct they are referring to.

但是,修复该错误并不能解决问题。我得到 lambda表达式在未评估的上下文错误下面的代码:

However, fixing that error does not solve the problem. I get lambda-expression in unevaluated context error for the following code:

struct A {int x; int y;};
typedef decltype ([](const A lhs, const A &rhs) ->bool {
    return lhs.x < rhs.x;
    }) Comp;
std::set <A, Comp > SetOfA;


推荐答案

std :: set 需要一个类型,而不是一个 表达式,所以它只是你错误地使用。

The 2nd template parameter of std::set expects a type, not an expression, so it is just you are using it wrongly.

您可以这样创建集合:

auto comp = [](const A& lhs, const A& rhs) -> bool { return lhs.x < rhs.x; };
auto SetOfA = std::set <A, decltype(comp)> (comp);

这篇关于如何使用lambda表达式作为模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆