mardi 18 février 2020

Member function template to call a funcion on a data member with arbitrary arguments

I'm working on a C++11 code base and wondering how I can call any function on a member type passing arbitrary arguments. Note that since I'm using C++11 I can't use something like std::invoke.

I started creating a function template in the Outer class, but my initial try gives me a compile error.

#include <iostream>
#include <utility>
#include <type_traits>

struct Inner {
  void bar(int x) {
    std::cout << "Called: x=" << x << std::endl;
  }
};

struct Outer {
  explicit Outer(Inner *i) : b{i} {}
  void foo(int) {}
  Inner* b;

  template <typename Func, typename ... Args>
  void CallInner(Func&& f, Args&& ... args) {
    b->f(std::forward<Args>(args)...);
  }
};


int main() {
  Inner inner{};
  Outer outer(&inner);
  outer.CallInner(&Inner::bar, 5);
}

Try it out yourself

Again, I would like to keep the signature of the function CallInner unchanged from the above sample code.

Aucun commentaire:

Enregistrer un commentaire