我已经阅读了多个关于将 lambda 传递给类模板的答案,但由于某种原因我无法实现它......我正在使用 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。
最佳答案
可以,但需要先在模板参数外声明,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;
关于c++ - lambda 可以作为 C++17 中的模板参数传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58717819/