【问题标题】:How to get types from variadic parameter pack in generic lambda?如何从泛型 lambda 中的可变参数包中获取类型?
【发布时间】:2017-05-17 01:50:45
【问题描述】:

我正在尝试编写一个函数,该函数将返回带有可变参数的generic lambda,其中 lambda 会检查其中一个参数是否等于特定值。这是(大致)我正在尝试做的事情:

template <int Index, typename TValue>
inline auto arg_eq(const TValue& value) 
{
    return [value] (auto... args) -> bool {
        return (std::get<Index>(std::tuple</* ??? */>(args...)) == value);
    };
}

我不确定在 std::tuple&lt;/* ??? */&gt; 模板参数中添加什么。我尝试了decltype(args)decltype(args...)autoauto... 和其他一些东西,但我不断收到编译器错误。这甚至可能吗?

非泛型等价物是这样的:

template <int Index, typename TValue, typename... TArgs>
inline auto arg_eq(const TValue& value)
{
    return [value] (TArgs... args) -> bool {
        return (std::get<Index>(std::tuple<TArgs...>(args...)) == value);
    };
}

这很好用,但返回的 lambda 不是通用的 - 它不适用于任何任意参数包。

【问题讨论】:

    标签: c++ lambda c++14 variadic-templates generic-lambda


    【解决方案1】:

    你可以通过简单地使用std::make_tuple来避免提及类型:

    template <int Index, typename TValue>
    auto arg_eq(const TValue& value) 
    {
        return [value] (auto... args) -> bool {
            return (std::get<Index>(std::make_tuple(args...)) == value);
        };
    }
    

    【讨论】:

      【解决方案2】:

      我不确定在 std::tuple 模板参数中添加什么。我已经尝试过 decltype(args)、decltype(args...)、auto、auto... 和其他一些东西,但我不断收到编译器错误。

      试试

      std::tuple<decltype(args)...>
      

      完整的功能

      template <int Index, typename TValue>
      inline auto arg_eq(const TValue& value) 
      {
          return [value] (auto... args) -> bool {
              return (std::get<Index>(std::tuple<decltype(args)...>(args...)) 
                       == value);
          };
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-27
        • 1970-01-01
        • 1970-01-01
        • 2014-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多