【问题标题】:how to pass lambda express as parameter into mermber function in variadic template class如何将 lambda express 作为参数传递给可变参数模板类中的成员函数
【发布时间】:2017-06-30 01:21:34
【问题描述】:

我想设计一个带有元组的模板类,提供该类的 apply() 成员函数,该函数接受一个返回元组的 lambda 函数。 lambda 的返回元组的类型应该与模板类的类型列表兼容。但它无法编译。

main.cpp: In function ‘int main()’:
warning: lambda templates are only available with -std=c++14 or -std=gnu++14
     auto getTuple = []<typename ... Param, typename ... Types>(const Param & ..
                   ^
main.cpp: In lambda function:
main.cpp:75:32: error: parameter packs not expanded with ‘...’:
         std::tuple<Types>  items = std::tuple<Types>(p...);
                            ^
main.cpp:75:32: note:         ‘Types’
main.cpp:19:43: error: invalid use of ‘auto’
     std::tuple<Types...>  t = getTuple(param...);    

#include <iostream>
#include <tuple>
#include <string>
#include <type_traits>
#include <array>
template <typename... Types>
class Data
{
public:
    template<typename ... Param, typename Functor>
    std::tuple<Types...> apply(Functor getTuple, const Param& ... param)
    {
        std::tuple<Types...>  t = getTuple(param...);
        return t;
    }
};

int main()
{
    Data<std::string, int,double> data1;
    auto getTuple = []<typename ... Param, typename ... Types>(const Param & ... p)
    {
        std::tuple<Types>  items = std::tuple<Types>(p...);
        return items;
    };
    const auto t = data1.apply(getTuple , "hello", 3,1.9);

    return 0;
}

【问题讨论】:

    标签: c++ lambda parameters tuples variadic


    【解决方案1】:

    你不能给 lambda 模板:你可以简单地使用 auto 代替:

    auto getTuple = [](const auto& ... p)
    {
        auto items = std::make_tuple(p...);
        return items;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2014-10-20
      • 1970-01-01
      • 2013-11-06
      • 2017-06-14
      • 1970-01-01
      • 2015-09-10
      相关资源
      最近更新 更多