代码之家  ›  专栏  ›  技术社区  ›  RC.

使用STL绑定多个函数参数

  •  5
  • RC.  · 技术社区  · 16 年前

    在过去,我使用bind1st和bind2nd函数在STL容器上进行直接操作。我现在有一个MyBase类指针的容器,为了简单起见,这些指针如下所示:

    class X
    {
    public:
        std::string getName() const;
    };
    
    

    我想使用for_each调用以下静态函数,并将第一个和第二个参数绑定为:

    StaticFuncClass::doSomething(ptr->getName(),funcReturningString());

    我将如何分别使用_和绑定此函数的两个参数?

    我正在寻找以下线索:

    for_each(ctr.begin(), ctr.end(), 
             bind2Args(StaticFuncClass::doSomething(), 
                       mem_fun(&X::getName), 
                       funcReturningString());
    

    我看到Boost提供了一个自己的绑定函数,它看起来很有用,但是STL解决方案是什么呢?

    提前感谢您的回复。

    3 回复  |  直到 16 年前
        1
  •  13
  •   Stack Overflow is garbage    16 年前

    当绑定语法变得太奇怪时,一个可靠的退路是定义自己的函子:

    struct callDoSomething {
      void operator()(const X* x){
        StaticFuncClass::doSomething(x->getName(), funcReturningString());
      }
    };
    
    for_each(ctr.begin(), ctr.end(), callDoSomething());
    

    bind 不管怎样,函数都是在幕后进行的。

        2
  •  4
  •   UncleZeiv    16 年前

    “STL解决方案”将是编写自己的活页夹。。。这就是为什么他们创建了强大的boost::bind。

        3
  •  3
  •   xtofl Adam Rosenfield    16 年前

    您可以创建一个本地函子结构,该结构可以由编译器内联(如Jalf所示),也可以使用一个简单的函数:

    void myFunc( const X* x ) { 
        StaticFuncClass::doSomething(x->getName(), funcrReturningString() ); 
    }
    
    for_each( c.begin(), c.end(), myFunc );