C++20 是否允许衰减为函数指针的非捕获 lambda 直接作为非类型模板参数传递?如果是这样,正确的语法是什么?
我已经在各种版本的 clang 和 gcc 中使用-std=c++2a.
#include <iostream>
template<auto f>
struct S {
static void invoke(int x) { f(x); }
};
using X = S<+[](int x) -> void { std::cout << x << " hello\n"; }>;
int main()
{
X::invoke(42);
}
Run Code Online (Sandbox Code Playgroud)
gcc 毫无怨言地编译代码,代码按预期运行。
clang 编译失败并出现以下错误:
error: a lambda expression cannot appear in this context
using X = S<+[](int x) -> void { std::cout << x << " hello\n"; }>;
^
Run Code Online (Sandbox Code Playgroud)
这是完整的代码(在线版本):
Clang 10.0.0 头:https …
我使用 NTTP(非类型模板参数)lambdastring_view在编译时将 a 存储到类型中:
template<auto getStrLambda>
struct MyType {
static constexpr std::string_view myString{getStrLambda()};
};
int main() {
using TypeWithString = MyType<[]{return "Hello world";}>;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这有效,并实现了我的主要目的。
我现在的问题是,为了使其更易于使用,我如何编写一个包装函数来为我创建 lambda?
我在想这样的事情:
// This helper function generates the lambda, rather than writing the lambda inline
consteval auto str(auto&& s) {
return [s]() consteval {
return s;
};
};
template<auto getStrLambda>
struct MyType {
static constexpr std::string_view myString{getStrLambda()};
};
int main() {
using TypeWithString = MyType<str("Hello world")>; …Run Code Online (Sandbox Code Playgroud)