5

I am struggling with C++ templates, functions and bind.

Let's say my class A is like this :

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 like this :

    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 with a member function of A in parameter, like this (or something like this) :

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

The three ??? would be the type of the second paramter. Since I'm pretty new to std::function, std::bind and templates, I tried what I already knew to use but I always got compilation errors.

So how to do it ?

1 Answers1

7

The syntax for a standard member function is Ret (Class::*) (Args...). In your case, this 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 syntax you desire:

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

If you want to use std::function, you'll need to wrap your member function with something that takes the implicit object parameter using a lambda or std::bind or similar.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193