【发布时间】: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