Background
I am using a NTTP (non-type template parameter) lambda to store a string_view into a type at compile time:
template<auto getStrLambda>
struct MyType {
static constexpr std::string_view myString{getStrLambda()};
};
int main() {
using TypeWithString = MyType<[]{return "Hello world";}>;
return 0;
}
This works, and achieves my main intention.
Question
My question now is, to make this easier to use, how can I write a wrapper function to create the lambda for me?
I'm thinking something like:
// 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")>;
return 0;
}
The above fails on clang since the lambda isn't structural, since it needs to capture the string:
error: type '(lambda at <source>:4:12)' of non-type template parameter is not a structural type
using TypeWithString = MyType<str("Hello world")>;
^
note: '(lambda at <source>:4:12)' is not a structural type because it has a non-static data member that is not public
return [s]() consteval {
^
Given that it's possible for a lambda to use a variable without capturing it if the variable is initialized as a constant expression (source), how can I define a function to parameterize this lambda return value at compile time?