首页 > 解决方案 > 如何将 lambda 传递给模板参数

问题描述

我正在尝试定义一个函数func(),它返回一个std::string.

template<typename T = std::string, template<typename> typename F = decltype([](const T &t){return t;})>
std::string func(const T &t){
    F f;
    return f(t);
}

如您所见,我要做的是传递一个 lambda 作为模板参数,以便我可以func()像这样调用函数:

func<int, decltype([](int a){return std::to_string(a);})>(2);

另外,我为模板参数设置了默认值,以便我可以这样调用它:

func<>("abc");

但是,上面的代码给了我一个错误:

<source>:39:54: error: expected unqualified-id before 'decltype'
   39 | template<typename T, template<typename> typename F = decltype([](const T &t){return t;})>
      |                                                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:39:54: error: invalid default argument for a template template parameter
<source>:39:54: error: expected '>' before 'decltype'

顺便说一句,我的 C++ 版本是 C++11。

标签: c++c++11templateslambdatemplate-argument-deduction

解决方案


在 C++11 中,您不能在未评估的上下文中使用 lambda 表达式,因此我认为您必须以不同的方式实现它。

C++20 添加了这个特性,所以这里有一个将在 C++20 中编译和运行的示例。

#include <iostream>
#include <string>


template<typename T = std::string, typename F = decltype([](const T &t)->std::string{return t;})>
std::string func(const T &t){
    F f;
    return f(t);
}



int main() {
    // convert int to string
    std::cout << func<int, decltype([](int a){return std::to_string(a);})>(2) << std::endl;
    // take float parameter, but just ignore the parameter
    std::cout << func<float, decltype([](float a){return "ignore the param";})>(2.2) << std::endl;
    // default lambda
    std::cout << func("abc") << std::endl;

    return 0;
}

推荐阅读