C++11 使用 lambda 和 std::function 进行类型推理
C++11 type inference with lambda and std::function
我有以下代码片段,虽然完全是微不足道的,但说明了我试图在更通用的代码中使用的模式。
template<typename InT, typename ResT>
ResT unary_apply( InT val, std::function<ResT(InT)> fn )
{
return fn(val);
}
我希望能够使用函数指针、函子、lambda 等调用unary_apply:因此使用 std::function
将其全部抽象出来。
当我尝试通过以下方式使用上述内容时,C++(g++ 4.7)无法执行相关的类型推断:
double blah = unary_apply( 2, []( int v ) { return 3.0 * v; } );
失败
src/fun.cpp:147:75: error: no matching function for call to ‘unary_apply(int, test()::<lambda(int)>)’
src/fun.cpp:147:75: note: candidate is:
src/fun.cpp:137:6: note: template<class InT, class ResT> ResT unary_apply(InT, std::function<ResT(InT)>)
src/fun.cpp:137:6: note: template argument deduction/substitution failed:
src/fun.cpp:147:75: note: ‘test()::<lambda(int)>’ is not derived from ‘std::function<ResT(double)>’
而且我发现我必须显式指定模板参数(在实践中我相信它只是无法推断的返回类型):
double blah = unary_apply<int, double>( 2, []( int v ) { return 3.0 * v; } );
我对 C++11 中的类型推断规则不是很熟悉,但上述行为似乎确实合理(我可以看到通过 std::function
的内部机制进行推断可能是一个相当大的问题)。我的问题是:是否可以重写上面的 unary_apply
函数以保持相同的灵活性(就可以作为第二个参数传递的函数/函子等类型而言),同时还提供更多类型推断的线索,所以我不必在调用时显式提供模板参数?
多一点鸭子类型应该可以:
template <typename T, typename F>
auto unary_apply(T&& val, F&& func) -> decltype(func(val)) {
return func(std::forward<T>(val));
}
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 推理类型如何工作"auto"和按引用调用?
- CAN模板类型推理考虑原始操作类型转换
- 从函数指针对标准 C++98 中的函数类型参数进行静态推理
- 在C++11类型推理过程中,控制优先级的规则是什么
- C++11 类型推理如何在浮点数或双精度数之间做出决定
- 带有函子的自动类型推理不起作用
- C++11 使用 lambda 和 std::function 进行类型推理
- 矩阵积的 Cholesky 的特征和 C++11 类型推理失败
- 使用模板化复合类型推理实现unique_copy
- 不知道C++11类型推理