如何使用boost::bind从参数中实时提取数据

How to extract data on-fly from the argument with boost::bind

本文关键字:实时 提取 数据 参数 何使用 boost bind      更新时间:2023-10-16

假设你正在传递一个函数给另一个函数:

foo(boost::bind( &CLASS_NAME::OnValueChanged, this, _1));

但问题是_1类型可以变化,我真的不需要它,只需要它的一个数据。所以我想这样写:

foo(boost::bind( &CLASS_NAME::OnValueChanged, this, _1.GetName()));

因为无论_1是什么类型,我知道每次都有GetName()方法,结果类型都是一样的(wstring)。

怎么做?

另外,在我的例子中,包含GetName的类型是一个模板

你只需要再绑定一次!

foo(boost::bind( &CLASS_NAME::OnValueChanged, this, boost::bind(GetNameFunctor(), _1));

GetNameFunctor()的通用实现如下所示

struct GetNameFunctor {
     typedef std::string result_type;
     template <typename T> std::string operator()(T const& o) const {
         return o.GetName();
     }
};

如果你想要更多的控制/支持,你可以看看

  • http://www.boost.org/doc/libs/1_55_0/doc/html/boost_typeerasure.html