获取可调用对象的输入/输出类型

Get input/output type of callable

本文关键字:输出 类型 输入 调用 对象 获取      更新时间:2023-10-16

我有以下问题:

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的输入/输出类型如何在编译时自动推导?

提前感谢。

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;
}

类型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<Func(T_in)>::type代替std::result_of_t<Func(T_in)>应该也适用于c++ 11,而不仅仅适用于c++ 14。

使用函数映射实际上非常常见的设计模式是c++。我建议您使用std::Map容器。这是一个链接。

祝你好运