How to specify a member function as a parameter?

I struggle with C ++ templates, functions and communication.

Let's say my class A as follows:

 class A { void set_enabled_for_item(int item_index, bool enabled); void set_name_for_item(int item_index, std::string name); int item_count(); } 

I would like to create a method in A as follows:

  template <typename T> void set_for_all_items(T value, ??? func) { auto count = trackCount(); for (auto i = 0; i < count; ++i) { func(i, value); } } 

So I could call it using the member function of parameter A in the parameter, like this (or something like this):

 auto a = new A; a->set_for_all_items("Foo Bar", &A::set_name_for_item); 

Three ??? are the type of the second parameter. Since I'm pretty new to std :: function, std :: bind and templates, I tried what I already knew, but I always had compilation errors.

So how to do this?

+5
source share
1 answer

The syntax for the standard member function is Ret (Class::*) (Args...) . In your case, it might look something like this (untested):

 template <typename T, typename Arg> void set_for_all_items(T value, void (A::* func) (int, Arg)) { auto count = trackCount(); for (auto i = 0; i < count; ++i) { (this->*func)(i, value); //note the bizarre calling syntax } } 

This will allow you to call with the desired syntax:

 auto a = new A; a->set_for_all_items("Foo Bar", &A::set_name_for_item); 

If you want to use std::function , you will need to wrap your member function with something that takes an implicit parameter of an object using lambda or std::bind or similar.

+7
source

All Articles