将 boost::function 与模板一起使用

Using boost::function with templates

我对 boost::function 和模板函数有疑问。场景如下;

我想 运行 另一个函数 "setter" 中的一个函数。我的功能类似于

data.totalSize(TotalSize);

totalSize 函数输入参数的类型为 "uint32_t",输出参数的类型为 "void"。

所以我决定使用boost::function;下面是我的代码:

setter(boost::bind(&myIDL::payload::totalSize,boost::ref(data),_1),(TotalSize));

并且 setter 实现是

template<typename Outer>
inline void setter(boost::function<void(Outer)> myFunc, Outer myValue)
{
   myFunc(myValue);
}

我会得到以下编译错误:

error: no matching function for call to setter(boost::_bi::bind_t<void, boost::_mfi::mf1<void,myIDL::payload, unsigned int>, boost::_bi::list2<boost::reference_wrapper<myIDL::payload>, boost::arg<1> > >, quint32&)'

看来boost::function不理解我的模板类型。所以我决定写成下面这样:

template<typename Outer>
inline void setter(boost::function<void(unit32_t)> myFunc, Outer myValue)
{
   myFunc(myValue);
}

而且有效!所以我想知道如何解决我的问题。在此先感谢您的帮助。

此致, 礼萨

模板参数类型推导仅推导类型,不考虑任何转换。 就像编译器没有通知你一样,boost::bind 的结果产生了一些不可描述类型的纯右值:

boost::_bi::bind_t<void, boost::_mfi::mf1<void,myIDL::payload
                       , unsigned int>
                       , boost::_bi::list2<boost::reference_wrapper<myIDL::payload>
                                         , boost::arg<1> > >

很明显,不同:

boost::function<void(Outer)>

也就是说,类型模板参数 Outer 不能从参数表达式的类型推导出来。一个解决方案是接受 any 函数对象:

template <typename F, typename Outer>
inline void setter(F myFunc, Outer myValue)
{
   myFunc(myValue);
}

或者将 Outer 放在非推导上下文中(并付出类型擦除的代价):

#include <boost/mpl/identity.hpp>

inline void setter(boost::function<void(typename boost::mpl::identity<Outer>::type)> myFunc
                 , Outer myValue)
{
   myFunc(myValue);
}