Intenté seguir Bjarne Stroustups explicación de la plantilla function
. Específicamente jugado con la intercambiabilidad de c-función triples, funtores, lambdas y funciones miembro de triplesC++ 0x función <>, enlace y miembros
Dadas las DEFINCIONES:
struct IntDiv { // functor
float operator()(int x, int y) const
{ return ((float)x)/y; }
};
// function pointer
float cfunc(int x, int y) { return (float)x+y; }
struct X { // member function
float mem(int x, int y) const { return ...; }
};
using namespace placeholders; // _1, _2, ...
que desea asignar a function<float(int,int)>
todo lo posible:
int main() {
// declare function object
function<float (int x, int y)> f;
//== functor ==
f = IntDiv{}; // OK
//== lambda ==
f = [](int x,int y)->float { return ((float)y)/x; }; // OK
//== funcp ==
f = &cfunc; // OK
// derived from bjarnes faq:
function<float(X*,int,int)> g; // extra argument 'this'
g = &X::mem; // set to memer function
X x{}; // member function calls need a 'this'
cout << g(&x, 7,8); // x->mem(7,8), OK.
//== member function ==
f = bind(g, &x,_2,_3); // ERROR
}
Y la última línea da un error típico de compilación-plantilla ilegible. suspiro.
Quiero vincular f
a una función existente de instancias x
, de modo que solo quede la firma float(int,int)
.
¿Cuál debe ser la línea en lugar de
f = bind(g, &x,_2,_3);
... o dónde si no es el error?
Antecedentes:
Aquí viene ejemplo Bjarnes para el uso de bind
y function
con una función miembro:
struct X {
int foo(int);
};
function<int (X*, int)> f;
f = &X::foo; // pointer to member
X x;
int v = f(&x, 5); // call X::foo() for x with 5
function<int (int)> ff = std::bind(f,&x,_1)
I pensébind
se utiliza de esta manera: Los lugares no asignado obtener placeholders
, el resto se completa en el bind
. ¿Debe la tuerca _1
obtener this
, luego`? Y por lo tanto la última línea será:
function<int (int)> ff = std::bind(f,&x,_2)
En Howards sugerencia a continuación lo probé :-)
¿Por qué no usar simplemente una lambda? – Puppy
¡Agradable! :-) ....... –