lundi 29 décembre 2014

bind binded function as argument

I have a class foo with a method bar which takes something callable (function-pointer/ functor). this callable something should be passed to another method doit as an binded element with a third method bar_cb method.



#include <functional>
#include <iostream>

class foo {
public:
template<typename T>
void bar(T&& t) {
std::cout << "bar\n";
doit(std::bind(&foo::template bar_cb<T>, this, std::forward<T>(t)));
}

template<typename T>
void doit(T&& t) {
std::cout << "doit\n";
t();
}

template<typename T>
void bar_cb(T&& t) {
std::cout << "bar_cb\n";
t();
}
};


void lala() {
std::cout << "lala\n";
}

class functor {
public:
void operator()() {
std::cout << "functor::operator()\n";
}
};


int main() {
foo f;
functor fn;
f.bar(fn);
f.bar(std::bind(lala)); // error

return 0;
}


This works fine for functors but not for binded functions as argument for foo::bar (lala in my example). Is it possible to pass an unknowable type to a method and bind it in this method as an argument to another (and if so how)?


I know I could wrap a functor (std::function for example) around the function but since I can call an unknowable type I think there is a way to also bind it (I think I'm just missing something simple).


Here an link to an example.


Aucun commentaire:

Enregistrer un commentaire