vendredi 23 février 2018

Passing member function pointer as template parameter

I want to create a wrapper class which is able to call member functions (of any type) of the wrapped class with help of templates. This is what I have so far:

template <typename T>
class wrapper {
  public:    
    template<typename R, R (T::*func)()>
    void call_func() {
      (wrapped.*func)();
    }

  private:
    T wrapped;  
};

class some_class {
  private:
    int i = 2;
  public:
    void some_func() {
      std::cout << i << std::endl;
    }
};

int main() {
    wrapper<some_class> wr;
    // How I need to call at the moment:
    wr.call_func<void, &some_class::some_func>();
    // How I want call:
    wr.call_func<&some_class::some_func>();
    return 0;
}

As you can see in the comments of the main function, I want to call the wrapper-function without explicitly specifying the return type of the wrapped member function. (How) Can this be done in C++11?

Aucun commentaire:

Enregistrer un commentaire