如何使用lambda表达式作为模板参数?

32 c++ lambda templates c++11

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

以下解决方案应该有效,因为lambda表达式只创建一个匿名结构,它应该适合作为模板参数.但是,产生了很多错误.

代码示例:

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

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

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
Run Code Online (Sandbox Code Playgroud)

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

编辑

有人指出,我正在使用lambda表达式错误,因为它们返回了他们所指的匿名结构的实例.

但是,修复该错误并不能解决问题.我收到lambda-expression in unevaluated context以下代码的错误:

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;
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 33

第二个模板参数std::set需要一个类型,而不是一个表达式,所以它只是你错误地使用它.

您可以像这样创建集合:

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

  • @buratina:如果*是*类型,那么`[](){} x;`应该是一个有效的声明.lambda表达式只是该匿名结构的*实例*.你需要一个`decltype`来获得那种类型. (11认同)