c++ - How to give a member function as a parameter? -
i struggling c++ templates, functions , bind.
let's class a
:
class { 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 create method in a
:
template <typename t> void set_for_all_items(t value, ??? func) { auto count = trackcount(); (auto = 0; < count; ++i) { func(i, value); } }
so call member function of in parameter, (or this) :
auto = new a; a->set_for_all_items("foo bar", &a::set_name_for_item);
the 3 ???
type of second paramter. since i'm pretty new std::function, std::bind , templates, tried knew use got compilation errors.
so how ?
the syntax standard member function ret (class::*) (args...)
. in case, might (untested):
template <typename t, typename arg> void set_for_all_items(t value, void (a::* func) (int, arg)) { auto count = trackcount(); (auto = 0; < count; ++i) { (this->*func)(i, value); //note bizarre calling syntax } }
this allow call syntax desire:
auto = new a; a->set_for_all_items("foo bar", &a::set_name_for_item);
if want use std::function
, you'll need wrap member function takes implicit object parameter using lambda or std::bind
or similar.
Comments
Post a Comment