[英]c++ std for_each define the std function later
我想更改此代碼:
std::for_each( container.begin(), container.end(), std::bind(&Class::method1, _1, param));
容器中具有指向Class的指針,該指針指向僅傳遞參數的版本:
// create the functor here ( bind to method1 or method2, etc)
// ....
//
std::for_each( container.begin(), container.end(), functor(param) );
我不能使用lambda。
容器可以是:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.