带有Boost的泛型函数bind()
Generic function bind() with Boost
我有一些c风格的函数,返回0
表示成功,返回!= 0
表示错误。
我想将它们"包装"到 void
函数中,throw
而不是返回值。
我已经写了这个帮助器:
void checkStatus(int status) {
if (status != 0)
// throw an error object
}
然后,为了包装一个确定函数int tilt(float degrees)
,我使用boost::bind
:
function<void(float)> ntilt = bind(checkStatus, bind(tilt, _1));
ntilt(30); // this will call checkStatus(tilt(30))
效果很好。但是我想有一个专门的包装函数,所以我可以这样做:
function<void(float)> ntilt = wrap(tilt);
ntilt(30); // this will call checkStatus(tilt(30))
它应该适用于任何返回int
的函数/签名。
使用Boost最好的方法是什么?
您可以创建多个重载来处理包装函数可能接受的不同数量的参数:
// handles 1 parameter functions
template<typename Ret, typename T0>
function<void(T0)> wrap(Ret (*fun)(T0)) {
return bind(checkStatus, bind(fun, _1));
}
// handles 2 parameters functions
template<typename Ret, typename T0, typename T1>
function<void(T0, T1)> wrap(Ret (*fun)(T0, T1)) {
return bind(checkStatus, bind(fun, _1, _2));
}
// ... add more
下面是c++ 11的实现。如果你不想要std::function
,你可以避免一些东西,但是,它可以工作:
#include <functional>
#include <stdexcept>
template<typename Ret, typename... Args>
struct wrapper {
typedef Ret (*function_type)(Args...);
void operator()(Args&&... args) {
if(fun(std::forward<Args>(args)...) != 0)
throw std::runtime_error("Error");
}
function_type fun;
};
template<typename Ret, typename... Ts>
std::function<void(Ts...)> wrap(Ret (*fun)(Ts...)) {
return std::function<void(Ts...)>(wrapper<Ret, Ts...>{fun});
}
相关文章:
- boost::bind()类似的东西,但用于函数调用
- PCL:当我在setConditionFunction中使用std::bind 时,没有合适的转换函数
- std::bind 是否实现了 std::ref 和 std::cref 来消除函数调用的歧义?
- std::bind 和 std::函数术语不值为接受 0 个参数?
- 在调用 std::bind 的产品后意外调用析构函数
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 我们应该在使用 std::bind 应用之前检查一个不为空的函数吗?
- 为什么 std::bind 静态类型检查传递给函数的参数?
- 对函数库中的语法感到困惑 std::bind
- 如何将参数从函数传递给 std::bind
- 如何在C++中使用 std::bind 函数作为信号处理程序?
- std::bind() 参数列表中函子的执行顺序(可能与函数参数的求值顺序无关)
- 在模板函数参数中使用 std::bind
- boost::bind函数缓冲区的最大大小
- 使用 std::thread & std::bind 在成员函数中启动线程
- 如何使用 gtest 对 std::bind 函数进行单元测试
- 将boost::bind函数存储在std::map中
- bind函数的输入参数错误
- 无法在 std::map 中存储 boost::bind 函数
- 将boost::bind函数传递给内部类时出错