Tom*_*Tom 3 c++ lambda templates c++20
假设我有一个 C++20 模板 lambda:
auto foo = []<bool arg>() {
if constexpr(arg)
...
else
...
};
Run Code Online (Sandbox Code Playgroud)
但是我怎么称呼它呢?我似乎找不到语法的描述。我尝试了通常的foo<true>();
and template foo<true>();
,但 gcc 似乎都不喜欢。
foo.template operator()<true>();
Run Code Online (Sandbox Code Playgroud)
是正确的语法。在Godbolt.org上试试
这种奇怪语法的原因是:
foo
是一个实现template<bool> operator()
方法的通用 lambda 。foo.operator()<true>()
将解释<
为比较运算符。如果你想有一个稍微更可读的语法,请尝试使用std::bool_constant
:
auto foo = []<bool arg>(std::bool_constant<arg>) {
...
};
foo(std::bool_constant<true>{});
Run Code Online (Sandbox Code Playgroud)