c++ - 获取可调用的输入/输出类型

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

我有以下问题:

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 映射到输入 vector input 的每个元素。我的问题如下:我希望输入 vector input 的元素具有 f 的输入类型(即 T_in),并且输出 vector 的元素 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;
}

关于c++ - 获取可调用的输入/输出类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40108966/

相关文章:

c++ - 询问变量在 C++ 中是什么数据类型

c++ - 使用 C++ constexpr 对 N 位字进行位反转

c++ - 优化字符串创建

java - 在Android Studio中运行ExecutorService时出现类异常错误

Ruby:BigDecimal:同时是一个类和一个方法?

java - 深入理解Java中的Reactive Programming

c++ - 是否可以将 int 添加到 pair 中?

c++ - 如何根据 OpenGL 规范安全地确保(在任何平台上)正确实现 char* 类型?

c++ - GCC 的模板模板参数推导失败(适用于 MSVC)

c++ - C++14 标准布局类型可以将 `alignas` 用于字段吗?