c++std for_each稍后定义std函数

c++ std for_each define the std function later

本文关键字:定义 std 函数 for each c++std      更新时间:2023-10-16

我想更改此代码:

std::for_each( container.begin(), container.end(), std::bind(&Class::method1, _1, param));

其中容器有指向Class的指针,指向只会传递param:的版本

// create the functor here ( bind to method1 or method2, etc)
// ....
//
std::for_each( container.begin(), container.end(), functor(param) );

我不能用lambdas。

容器可以是:

 std::list<Class*>
struct functor {
    int param;
    functor(int param): param(param) {}
    void operator()(Class* c) {
        c->method1(param);
    }
};

给你。一个函子类,可以完全用作您的示例。没有lambda,就没有绑定到方法。只需将参数传递给构造函数。您可以将成员函数指针传递给构造函数,或者将其扩展到模板,以避免为每个方法编写一个指针。

或者,如果你只是想先选择方法,然后再绑定参数,你可以这样做:

// create the functor here ( bind to method1 or method2, etc)
std::function<void(Class*,decltype(param))> functor(&Class::method1); // "bind" the method
// ....
std::for_each( container.begin(), container.end(), std::bind(functor, _1, param) ); // bind the param

请注意,我认为这样做没有任何好处,而不是你问题中的第一行代码。

您想要一些东西来生成函子。

这是你想要的一般函子。

template< typename CLASS, typename CLASS_METHOD, typename PARAM_TYPE >
class Functor
{
    CLASS_METHOD m_method; // actually will be of type void(CLASS::*func)( PARAM_TYPE )
    PARAM_TYPE m_param;
 public:
    void operator()( CLASS * c ) const
    {
       (c->*m_method)( m_param );
    }
};
template typename< CLASS, CLASS_METHOD, PARAM_TYPE > 
Functor< CLASS, CLASS_METHOD, PARAM_TYPE > 
functor( CLASS_METHOD method, PARAM_TYPE param )
{
      return Functor< CLASS, CLASS_METHOD, PARAM_TYPE >( method, param );
}
std::for_each
  ( 
    container.begin(), container.end(), 
    functor< Class >( &Class::method1, param );
  );

如果你愿意,我们可以让它成为非模板。

class Functor
{
     typedef void (Class::*func_type )(int);
     func_type m_method; // assuming that's the param type
     int m_param;
public:
     Functor( func_type method, int param )
         : m_method( method ), m_param( param )
     {
     }
     void operator()( Class * c ) const
     {
        (c->*m_method)(param);
     }
};
std::for_each( container.begin, container.end(), Functor( &Class::method1, param ) );

现在,为了"仅"指定参数,您为每个"方法"编写函数,因此:

Functor method1Functor( int param )
{
      return Functor( &Class::method1, param );
}
Functor method2Functor( int param )
{
    return Functor( &Class::method2, param );
}

现在在您的代码中:

std::for_each( container.begin(), container.end(), method1Functor( param ) );

您也可以编写这些函数方法来执行bind并返回std::function