lo usé mucho tiempo volver para crear un grupo de subprocesos de plugin en C++; Dado que la función estaba tomando tres parámetros que se pueden escribir como este
Suponga que su método tiene la firma:
int CTask::ThreeParameterTask(int par1, int par2, int par3)
Para crear un objeto de función para unir los tres parámetros que se pueden hacer como esto
// a template class for converting a member function of the type int function(int,int,int)
//to be called as a function object
template<typename _Ret,typename _Class,typename _arg1,typename _arg2,typename _arg3>
class mem_fun3_t
{
public:
explicit mem_fun3_t(_Ret (_Class::*_Pm)(_arg1,_arg2,_arg3))
:m_Ptr(_Pm) //okay here we store the member function pointer for later use
{}
//this operator call comes from the bind method
_Ret operator()(_Class *_P, _arg1 arg1, _arg2 arg2, _arg3 arg3) const
{
return ((_P->*m_Ptr)(arg1,arg2,arg3));
}
private:
_Ret (_Class::*m_Ptr)(_arg1,_arg2,_arg3);// method pointer signature
};
Ahora, para enlazar los parámetros, tenemos que escribir una función de enlace. Por lo tanto, aquí va:
template<typename _Func,typename _Ptr,typename _arg1,typename _arg2,typename _arg3>
class binder3
{
public:
//This is the constructor that does the binding part
binder3(_Func fn,_Ptr ptr,_arg1 i,_arg2 j,_arg3 k)
:m_ptr(ptr),m_fn(fn),m1(i),m2(j),m3(k){}
//and this is the function object
void operator()() const
{
m_fn(m_ptr,m1,m2,m3);//that calls the operator
}
private:
_Ptr m_ptr;
_Func m_fn;
_arg1 m1; _arg2 m2; _arg3 m3;
};
Y, una función de ayuda para utilizar la clase binder3 - bind3:
//a helper function to call binder3
template <typename _Func, typename _P1,typename _arg1,typename _arg2,typename _arg3>
binder3<_Func, _P1, _arg1, _arg2, _arg3> bind3(_Func func, _P1 p1,_arg1 i,_arg2 j,_arg3 k)
{
return binder3<_Func, _P1, _arg1, _arg2, _arg3> (func, p1,i,j,k);
}
y aquí nos cómo llamamos
F3 f3 = PluginThreadPool::bind3(PluginThreadPool::mem_fun3(
&CTask::ThreeParameterTask), task1,2122,23);
Nota: f3(); llamará al método task1-> ThreeParameterTask (21,22,23);
Para detalles más morbosos ->http://www.codeproject.com/Articles/26078/A-C-Plug-in-ThreadPool-Design
También es práctico para las devoluciones de llamada a funciones miembro: 'miThread = impulso :: hilo (boost :: bind (y MyClass :: threadMain, este))' – rlduffy
Buena explicación de bind. Pero ¿qué pasa con 'std :: function'? – RedX
Tu ejemplo 'pow' no se compila. Como 'pow' es una función sobrecargada, debe especificar manualmente qué sobrecarga. El enlace no puede dejar que sea deducido por la persona que llama del funtor resultante. P.ej. 'std :: transform (vec.begin(), vec.end(), out.begin(), std :: bind ((double (*) (double, int)) std :: pow, _1, 7)) ; ' –