lambda是否可以在C ++ 17中作为模板参数传递?

问题描述 投票:0回答:1

我已经阅读了关于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。

c++ g++ c++17
1个回答
0
投票

是,但是首先需要在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;

C++20 Live example

C++17 Live example

© www.soinside.com 2019 - 2024. All rights reserved.