[英]Can a lambda be passed a as a template parameter in C++17?
I've read multiple answers on SO with lambdas being passed to class templates but for some reason I cant achieve it... I am using g++ version 9 with C++17 being used.我已经阅读了关于 SO 的多个答案,其中 lambdas 被传递给 class 模板,但由于某种原因我无法实现它......我正在使用 g++ 版本 9 并使用 C++17。
#include <string>
struct Type {
Type();
Type(int);
int theVal();
};
template<typename Key, typename Value, Key(*KeyFunc)(Type t) = nullptr>
struct MyClass {
MyClass(){}
~MyClass(){}
void add(const Key key, const Value value){
//do stuff
}
void add(const Value value){
this->add(KeyFunc(value), value);
}
};
int main(){
MyClass<
int,
std::string,
+[](Type t){
return t.theVal();
}
> instance;
Type value(100);
instance.add(value);
return 0;
}
The error message tells me I cant have a lambda in a template.错误消息告诉我模板中不能有 lambda。
Yes, but it need to first declared outside the template parameter, and the lambda must be captureless:可以,但需要先在模板参数外声明,并且lambda必须是无捕获的:
auto lambda = [](Type t) {
return t.theVal();
};
// Works, C++17 allows constexpr conversion for nttp
MyClass<int, Type, lambda> instance;
In C++20, you can use C++17's auto
template parameter and a lambda directly in the template parameters:在 C++20 中,您可以直接在模板参数中使用 C++17 的auto
模板参数和 lambda:
constexpr auto noop = [](auto&& v) -> decltype(auto) {
return static_cast<decltype(v)&&>(v);
};
template<typename Key, typename Value, auto KeyFunc = noop>
class MyClass {
// ...
};
MyClass<
int,
Type,
[](Type t) {
return t.theVal();
}
> instance;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.