对模板使用boost::函数

Using boost::function with templates

本文关键字:boost 函数      更新时间:2023-10-16

我对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::函数不理解我的模板类型。所以我决定这样写:

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

它有效!所以我想知道如何解决我的问题。提前感谢你的帮助。

最诚挚的问候,Reza

模板参数类型推导仅推导类型,它不考虑任何转换。就像编译器不会不通知您一样,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。一个解决方案是接受任何函数对象:

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);
}