【发布时间】:2015-08-31 09:52:56
【问题描述】:
我有以下签名的方法:
template<typename T>
void
register_msg_action(const pmt::pmt_t& name,
boost::function<T(pmt::pmt_t)> converter,
boost::function<void(T)> action)
(pmt_t 是一个完整的类型,在你问之前)
以及采用 T converter(pmt::pmt_t) 和 void converter(T) 的重载(即原始 C/C++ 函数),以及上述 boost::function<> 和 C 样式函数参数的所有排列。这已经给我留下了 4 种不同的方法。
我想避免进一步增加方法的数量。但是,我会做的最常见的事情是调用类似
register_msg_action(pmt::mp("key"),
pmt::to_long, /* "raw" function long(pmt_t) */
boost::bind(&my_class::void_method_of_long, this, _1) /* CAVEAT */
);
我的方法是 /* CAVEAT */ 参数可以隐式转换为 boost::function<void(T)>,但是,情况似乎并非如此(g++ 5.1.1):
error: no matching function for call to ‘register_msg_action(pmt::pmt_t, boost::function<long int(boost::intrusive_ptr<pmt::pmt_base>)>&, boost::_bi::bind_t<void, void (*)(long int), boost::_bi::list1<boost::arg<1> > >)’
register_msg_action(pmt::mp("hi"), long_function, boost::bind(&my_class::void_method_of_long, this ,_1));
... 所有其他候选者 (boost::function,boost::function); (T(pmt_t),boost::function); (T(pmt_t), void(T)) ...
test.cc:56:1: note: candidate: template<class T> void register_msg_action(const pmt_t&, T (*)(pmt::pmt_t), boost::function<void(T)>)
register_msg_action(const pmt::pmt_t& name,
^
test.cc:56:1: note: template argument deduction/substitution failed:
test.cc:80:76: note: ‘boost::_bi::bind_t<void, void (*)(long int), boost::_bi::list1<boost::arg<1> > >’ is not derived from ‘boost::function<void(T)>’
register_msg_action(pmt::mp("key"), pmt::to_long, boost::bind(&my_class::void_method_of_long, this, _1));
现在,做
boost::function<void(long)> action (boost::bind(&my_class::void_method_of_long, this, _1));
register_msg_action(pmt::mp("key"), pmt::to_long, action);
效果很好。由于在boost::function 中甚至有一个构造函数使用boost::_bi::bind_t,我想知道我必须做什么才能使这项工作,没有
- 重新实现
boost::function - 依赖 C++11 或更高版本(不能这样做,旧版编译器支持)
- 使用
boost:phoenix进行函数式编程(会尝试这个,但我们必须支持的boost 版本还没有phoenix。
我害怕将第三个参数的类型添加为附加模板类型名,因为这会破坏保证action(converter(pmt::pmt_t)) 工作所必需的参数列表类型安全性,老实说,我宁愿处理更多代码现在而不是稍后检查用户的模板化 g++ 错误。
【问题讨论】:
标签: c++ implicit-conversion c++03 boost-bind boost-function