代码之家  ›  专栏  ›  技术社区  ›  Zack The Human Kunal

std::for_each,使用引用参数调用成员函数

  •  8
  • Zack The Human Kunal  · 技术社区  · 17 年前

    我有一个指针容器,我想迭代它,调用一个成员函数,该函数有一个作为引用的参数。如何使用STL实现这一点?

    我当前的解决方案是使用boost::bind和boost::ref作为参数。

    // Given:
    // void Renderable::render(Graphics& g)
    //
    // There is a reference, g, in scope with the call to std::for_each
    //
    std::for_each(
      sprites.begin(),
      sprites.end(),
      boost::bind(&Renderable::render, boost::ref(g), _1)
    );
    

    一个相关的问题(我从中得出当前的解决方案)是 boost::bind with functions that have parameters that are references . 这专门询问如何使用boost实现这一点。我在问怎么做 没有 促进

    编辑 :有一种方法可以不使用任何 boost . 利用 std::bind 同样的代码可以在C++11兼容的编译器中编写和编译,如下所示:

    std::for_each(
      sprites.begin(),
      sprites.end(),
      std::bind(&Renderable::render, std::placeholders::_1, std::ref(g))
    );
    
    2 回复  |  直到 8 年前
        1
  •  5
  •   dirkgently    17 年前

    <functional> . 您必须使用boost::bind或tr1::bind。