【问题标题】:Using boost::function with templates使用带有模板的 boost::function
【发布时间】:2015-10-13 06:54:24
【问题描述】:

我对 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::function,让编译器推断出函数对象的类型。 boost::function 无法从 boost::bind 返回的内容中推断出来
  • 亲爱的@Prior,你能解释一下吗?其实我没有得到你的解决方案。

标签: c++ templates boost bind


【解决方案1】:

模板参数类型推导仅推导类型,不考虑任何转换。 就像编译器没有通知你一样,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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    相关资源
    最近更新 更多