获取可调用对象的输入/输出类型
Get input/output type of callable
我有以下问题:
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
的输入/输出类型如何在编译时自动推导?
提前感谢。
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;
}
类型T_in
可以从input
向量中推断出来。
我认为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 < input.size() ; ++i )
res[ i ] = f( input[ i ] );
return res;
}
使用typename std::result_of<Func(T_in)>::type
代替std::result_of_t<Func(T_in)>
应该也适用于c++ 11,而不仅仅适用于c++ 14。
使用函数映射实际上非常常见的设计模式是c++。我建议您使用std::Map容器。这是一个链接。
祝你好运
相关文章:
- 在 C++ 中输出枚举类类型的向量元素
- 为什么在这种情况下,bool 类型的输出等于 0?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 无法在 HEVC 解码器上设置输出类型 IMFTransform
- 我的代码中是否有任何类型的错误,因为它没有给出正确的输出
- 来自 decltype 的意外输出类型
- 输出一个数字,该数字可能是三种类型之一
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 为什么给我输出 2 我使用类型转换?
- 如何在编译过程中输出C 类型信息
- 正在输出类型向量的成员类型
- 输出类型类的向量
- 使用DirectX获取显示设备输出类型
- 如何用我的c++代码中的vlcsdk控制视频输出类型
- 为输入类型选择模板输出类型
- 获取类定义中可调用对象的输入/输出类型
- 获取可调用对象的输入/输出类型
- 如何处理信号处理库的输入/输出类型
- 设置MP3编码器mft输出类型失败