C++20模板lambda:如何指定模板参数?
假设我有一个 C++20 模板 lambda:
auto foo = []<bool arg>() {
if constexpr(arg)
...
else
...
};
但是我怎么称呼它呢?我似乎找不到语法的描述。我尝试了通常的foo<true>();and template foo<true>();,但 gcc 似乎都不喜欢。
回答
foo.template operator()<true>();
是正确的语法。在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>{});
在Godbolt.org上试试