对模板使用boost::函数
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::函数不理解我的模板类型。所以我决定这样写:
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);
}
相关文章:
- 我正在将一个 std::string 传递给一个 boost 函数,该函数对该类型进行常量引用,但该值发生了变化
- 如何将Boost ::函数对象与所有参数绑定
- 从boost ::函数中提取参数
- Boost绑定和Boost函数,将带有参数的函数存储在向量中,然后执行它们
- 如何获得返回自身的boost::函数(或其他通用函数包装器)
- Boost函数赋值引发异常
- 正在从带有参数的new_ptr的boost::lambda::bind中获取boost::函数
- boost::函数与函数指针
- boost::函数参数定义不起作用
- 将boost::函数克隆到指针中,并用该指针调用封装的函数
- 使用boost::函数绑定到重载方法
- 如何使用boost函数来转换参数类型
- Boost::函数绑定的成员函数无效
- boost::函数与函数模板
- 如何将两个独立的boost::bind()组合为一个boost::函数
- boost元组导致boost绑定/boost函数出现问题
- 为什么某些 Boost 函数不需要以命名空间为前缀
- 从函数指针创建boost::函数的跨平台方法
- 传递boost::函数,该函数接受一个模板实参作为默认为NULL的形参
- 对模板使用boost::函数