C++ 作为boost::bind复合链的一部分取消引用迭代器

C++ 作为boost::bind复合链的一部分取消引用迭代器,c++,boost,bind,composite,dereference,C++,Boost,Bind,Composite,Dereference,我正在尝试使用bind生成一个函数: 收到一张地图 首先返回m.begin()-> 为此,我尝试使用boost::bind: typedef map<int,int>::const_iterator (map<int,int>::*const_begin_end) () const; bind(&pair<const int,int>::first, bind(static_cast<const_begin_end>(&map&

我正在尝试使用bind生成一个函数:

  • 收到一张地图
  • 首先返回m.begin()->
为此,我尝试使用boost::bind:

typedef map<int,int>::const_iterator (map<int,int>::*const_begin_end) () const;
bind(&pair<const int,int>::first, bind(static_cast<const_begin_end>(&map<int, int>::begin), _1));
typedef映射::常量迭代器(映射:*常量开始\结束)()常量;
绑定(&pair::first,绑定(static_cast(&map::begin),_1));
这不起作用,因为需要取消引用begin的结果。我的想法是

bind(&pair<const int,int>::first, bind(&operator*, bind(static_cast<const_begin_end>(&map<int, int>::begin), _1)));
bind(&pair::first,bind(&operator*,bind(static_cast(&map::begin),_1));
但这不起作用,因为没有全局操作符*

问题:

  • 使用boost::bind复合链可以实现这一点吗?怎么做
  • 更容易阅读的替代方案

您可以使用成员函数指针调用bind,成员运算符只是成员函数:

 const_begin_end pBegin = &map<int,int>::begin;
 x = bind(&std::pair::first, 
    bind(&std::map<int, int>::const_iterator::operator*, 
      bind(pBegin, _1)
    );
const\u begin\u end pBegin=&map::begin;
x=绑定(&std::对::第一,
绑定(&std::映射::常量迭代器::运算符*,
绑定(pBegin,_1)
);
但说真的,您也可以编写一个适当的函数来完成您需要的功能,而不是那种不可读的boost.bind混乱(您能说“可维护性”吗?)

因此,对于C++03,函数:

template <class Map>
typename Map::key_type keyBegin(Map const& m)
{ 
  return m.begin().first;
}
模板
类型名称映射::键\类型键开始(映射常量&m)
{ 
首先返回m.begin();
}
或C++03函子(可以在函数内部本地定义)

struct键开始
{
typedef std::map IntMap;
int运算符()(IntMap const&m){
首先返回m.begin();
}
};
或C++11 lambda(比绑定狂欢更具可读性):

autokeybeagin=[](std::map const&m)->int{
返回std::begin(m).first;
};
我强烈推荐,在C++03中动态编写函子时,它是我的首选库。它是Boost.Bind的一个更好的替代品——该库正显示出它的时代

例如,Phoenix允许我们在其函子上使用运算符来表示调用该函子时该运算符的实际用法。因此,
arg1+arg2
是一个返回其前两个操作数之和的函子。这大大减少了
bind
噪声。第一次尝试可能如下所示:

bind(&pair<const int, int>::first
     , *bind(static_cast<const_begin_end>(&map<int, int>::begin), arg1)) )
()


最后,我要补充一点,C++11绑定表达式的指定使得指向成员的指针可以处理任何使用
运算符*
的操作

bind(&pair<const int, int>::first, bind(static_cast<begin_type>(&std::map<int, int>::begin), _1))
bind(&pair::first,bind(static_cast(&std::map::begin),_1))

()

也许我没有正确地解释自己,但我想要的东西不仅适用于map::const_迭代器,而且适用于任何迭代器(包括指针)。map只是一个例子。
bind(&pair<const int, int>::first
     , *bind(static_cast<const_begin_end>(&map<int, int>::begin), arg1)) )
// We don't need to disambiguate which begin member we want anymore!
bind(&pair<const int, int>::first, *begin(arg1))
bind(&pair<const int, int>::first, bind(static_cast<begin_type>(&std::map<int, int>::begin), _1))