問題描述
如何使用 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 表達式作為模板參數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!