【问题标题】:Get input/output type of callable获取可调用的输入/输出类型
【发布时间】:2017-02-27 18:28:54
【问题描述】:

我有以下问题:

template<typename Func, typename T_in = /*input type of Func */, typename T_out = /*output type of Func */>
std::vector<T_out> foo( Func f, const std::vector<T_in>& input)
{
  std::vector<T_out> res( input.size() );

  for( size_t i = 0 ; i < input.size() ; ++i )
    res[ i ] = f( input[ i ] );

  return res;
}


int main()
{
  // example for f(x) = x*x
  std::vector<float> input = { /* ... */ };
  auto res = foo( [](float in){ return in*in; }, input );

  return 0;
}

正如您在上面看到的,我尝试实现一个函数foo,它将函数f 映射到输入向量input 的每个元素。我的问题如下:我希望输入向量input 的元素具有f 的输入类型(即T_in),输出向量的元素具有f 的输出类型(即, T_out),但没有将f 的输入/输出类型显式传递给foo(因为代码的可读性更好)。有谁知道如何在编译时自动推断f 的输入/输出类型?

非常感谢。

【问题讨论】:

    标签: c++ c++14 callable template-argument-deduction


    【解决方案1】:

    使用函数映射实际上非常常见的设计模式是 c++。我建议您为此使用 std::Map 容器。 here is a link.

    祝你好运:)

    【讨论】:

    • 谢谢。为简单起见,我在上面的帖子中使用了一个简化的示例。不幸的是,我的真实示例无法使用标准库来实现。
    【解决方案2】:

    decltype 可以解决这个问题,同时将foo 的返回类型更改为auto。

    template<typename Func, typename T_in>
    auto foo( Func f, const std::vector<T_in>& input)
    {
      std::vector<decltype(f(input[0]))> res( input.size() );
    
      for( size_t i = 0 ; i < input.size() ; ++i )
        res[ i ] = f( input[ i ] );
    
      return res;
    }
    
    
    int main()
    {
      // example for f(x) = x*x
      std::vector<float> input = { /* ... */ };
      auto res = foo( [](float in){ return in*in; }, input );
    
      return 0;
    }
    

    【讨论】:

      【解决方案3】:

      类型T_in可以从input向量中推导出来。

      我认为T_out的推演是std::result_of_t的作品

      template <typename Func, typename T_in,
                typename T_out = std::result_of_t<Func(T_in)>>
      std::vector<T_out> foo( Func f, const std::vector<T_in>& input)
      {
        std::vector<T_out> res( input.size() );
      
        for( size_t i = 0 ; i < input.size() ; ++i )
          res[ i ] = f( input[ i ] );
      
        return res;
      }
      

      使用 typename std::result_of&lt;Func(T_in)&gt;::type 而不是 std::result_of_t&lt;Func(T_in)&gt; 应该也适用于 C++11,而不仅仅是 C++14。

      【讨论】:

        猜你喜欢
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 2014-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-09
        • 1970-01-01
        相关资源
        最近更新 更多