c++ - lambda 可以作为 C++17 中的模板参数传递吗?

标签 c++ g++ c++17

我已经阅读了多个关于将 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++20 Live example

C++17 Live example

关于c++ - lambda 可以作为 C++17 中的模板参数传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58717819/

相关文章:

c++ - 如何使用 C++ Expects 运算符?

c++ - Src 与二进制?

c++ - 将可执行文件与静态库的完整路径链接起来

c++ - 解析 GCC 打印的 C/C++ 编译错误

c++ - GNU C++ : unique_ptr. h 没有那个文件或目录

c++ - 程序接收信号 SIGILL,非法指令

c++ - 使用 range-v3 进行转换

c++ - 这个有界递归的程序是否有未定义的行为?

c++ - 是否有任何 pthread 函数在最后一个线程终止时调用某些东西?

c++ - 如何将 C++/Ogre3D 代码链接到 Haskell