我有以下问题:
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/