获取可调用的输入/输出类型 [英] Get input/output type of callable
问题描述
我有以下问题:
模板< typename Func,typename T_in = / * Func * typename T_out = / * 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 res [i] = f(input [i]);
return res;
}
int main()
{
// f(x)的示例= x * x
std :: vector< ; float> input = {/ * ... * /};
auto res = foo([](float in){return in * in;},input);
return 0;
}
如上所示,我尝试实现一个函数 foo
,它将一个函数 f
映射到输入向量 input
的每个元素。我的问题如下:我想要输入向量输入
的元素具有输入类型 f
, T_in
)和输出向量的元素 f
(即但没有将
f
的输入/输出类型显式地传递给 foo
以提高代码的可读性)。有人知道如何输入/输出类型的 f
可以在编译时自动推导?
c
$可以从 code>输入
向量。
我认为扣除 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 res [i] = f(input [i]);
return res;
}
使用 typename std :: result_of< Func )> :: type
而不是 std :: result_of_t< Func(T_in)>
对于C ++ 14。
I have the following problem:
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;
}
As you can see above, I try to implement a function foo
which maps a function f
to each element of an input vector input
. My problem is the following: I want the elements of the input vector input
to have the input type of f
(i.e., T_in
) and the elements of the output vector the output type of f
(i.e., T_out
) but without passing the input/output type of f
explicitly to foo
(due to a better readability of the code). Has anyone an idea how the input/output type of f
can be deduced automatically at compile time?
Many thanks in advance.
解决方案 The type T_in
can be deduced from the input
vector.
I think that the deduction of T_out
is a work for 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;
}
Using typename std::result_of<Func(T_in)>::type
instead of std::result_of_t<Func(T_in)>
should work also for C++11, not only for C++14.
这篇关于获取可调用的输入/输出类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!