lundi 26 septembre 2016

Convert from modern C++11 function to raw function pointer

Let's suppose I have the following function interface:

void giveme(void (*p)());

That function simply accepts a pointer to a function with no return type and argument.

I'm wondering if exists a way (without change the interface) to pass a class method as parameter of that function.

I'll try to explain better with an example. I have a class, like:

class Foo {
 public:
  template<typename T>
  void bar();
};

I want to pass bar<T> (of an addressable instance of the class) as parameter of the function giveme.

I thought to bind the method with an object, and obtain the function target.

Something like:

int main(int argc, char *argv[]) {
  Foo foo;
  std::function<void()> f = std::bind(&Foo::bar<int>, &foo);

  giveme(f.target<void()>());

  return 0;
}

It compiles, but obviously does not work because, from here:

TargetType shall match the target type, so that typeid(TargetType)==target_type(). Otherwise, the function always returns a null pointer.

So, if exists, what is a way to achieve it?

Aucun commentaire:

Enregistrer un commentaire