我已经阅读了关于lambdas传递给类模板的SO的多个答案,但是由于某些原因我无法实现它……我正在使用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;
}
错误消息告诉我模板中不能包含lambda。
是,但是首先需要在template参数之外声明,并且lambda必须是不可捕获的:
auto lambda = [](Type t){
return t.theVal();
};
// Works, C++17 allows constexpr conversion for nttp
MyClass<int, Type, lambda> instance;
在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;