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