【问题标题】:Get input/output type of callable within a class definition在类定义中获取可调用的输入/输出类型
【发布时间】:2017-02-27 20:17:53
【问题描述】:

我有以下问题:

template< typename Func >
class A
{
  public:
    A( Func f ) : _f( f ) {}

    // ...

    template< typename T_in = /*input type of _f */, typename T_out = /*output type of _f */ >
    std::vector<T_out> operator()( 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;
    }

  private:
    Func _f;
    // ...

};

template< typename Func >
A<Func> A_wrapper( Func f )
{
  return A<Func>( f );
}

int main()
{
  // example for f(x) = x*x
  std::vector<float> input = { /* ... */ };

  auto f          = []( float in ){ return in*in; };
  auto map_square = A_wrapper( f );

  auto res = map_square( input );

  return 0;
}

正如您在上面看到的,我尝试实现一个类 A,其函数 operator() 将函数 _f 映射到输入向量 input 的每个元素。

我的问题如下:我希望输入向量input 的元素具有_f 的输入类型(即T_in),输出向量的元素具有_f 的输出类型(即T_out)但没有将_f 的输入/输出类型显式传递给A 类,我用于类型推导的函数A_wrapper 和/或函数operator()(由于更好的代码可读性)。 有谁知道如何在编译时自动推断_f 的输入/输出类型?

非常感谢。

BTW:这里的问题和我之前的帖子Get input/output type of callable有关

【问题讨论】:

  • This 看起来像你想要的。

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


【解决方案1】:

Same question, same answer: 你可以从input 向量和T_out 使用std::result_of_t 推导出T_in

#include <vector>
#include <functional>

template< typename Func >
class A
{
  public:
    A( Func f ) : _f( f ) {}

    // ...

    template< typename T_in,
              typename T_out = std::result_of_t<Func(T_in)>>
    std::vector<T_out> operator()( 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;
    }

  private:
    Func _f;
    // ...

};

template< typename Func >
A<Func> A_wrapper( Func f )
{
  return A<Func>( f );
}

int main()
{
  // example for f(x) = x*x
  std::vector<float> input = { /* ... */ };

  auto f          = []( float in ){ return in*in; };
  auto map_square = A_wrapper( f );

  auto res = map_square( input );

  return 0;
 }

使用 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
    • 2020-12-11
    • 2020-07-02
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    相关资源
    最近更新 更多