![](/img/trans.png)
[英]C++17 - How to deduct the variadic parameter pack of a lambda passed as a template parameter?
[英]Can a lambda be passed a as a template parameter in C++17?
我已經閱讀了關於 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;
}
錯誤消息告訴我模板中不能有 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.