How to use a lambda expression as a template parameter?(如何使用 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-expression 错误:
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 的第二个模板参数需要 type,而不是 表达式,所以只是你用错了.
The 2nd template parameter of std::set expects a type, not an expression, so it is just you are using it wrongly.
您可以像这样创建集合:
You could create the set like this:
auto comp = [](const A& lhs, const A& rhs) -> bool { return lhs.x < rhs.x; };
auto SetOfA = std::set <A, decltype(comp)> (comp);
这篇关于如何使用 lambda 表达式作为模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 lambda 表达式作为模板参数?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
