Matt Stokes
Matt Stokes

Reputation: 4958

Template pass member function with args and return value as parameter c++

I would like to pass a templated function args for class and a method of that class to call. The method has arguments as well as a return value.

Here is what I have so far. I believe I'm getting a little tripped up on the templatized function syntax:

bar.h

    class Bar {
     public:
       Bar();
       int FuncBar(int arg1);
    }

foo.h

    template<typename A, int (A::*Method)()>
    int FuncTemplate(A* a, int bar_arg1) {
      ....
      return a->Method(bar_arg1)
    }


    class Foo { 
     public:
       explicit Foo(Bar* bar);

     private:
       void FuncFoo();
       Bar* bar_;
    }

foo.cc

    Foo::Foo(Bar bar) : bar_(bar) {};
    void Foo::FuncFoo() {
      ...
      int bar_arg1 = 0;
      FuncTemplate<Bar, &(*bar_)::FuncBar>(bar_, bar_arg1);
    }

Upvotes: 0

Views: 342

Answers (1)

R Sahu
R Sahu

Reputation: 206707

You need to use int (A::*Method)(int) as the function pointer type since the member function expects an int as an argument.

Also, the call to the member function needs to be (a->*Method)(bar_arg1). The syntax for calling member function using a member function is not very intuitive.

template<typename A, int (A::*Method)(int)>
int FuncTemplate(A* a, int bar_arg1) {
  ....
  return (a->*Method)(bar_arg1)
}

Also, you need to use &Bar::FuncBar to get a pointer to the member function, not &(*bar_)::FuncBar.

void Foo::FuncFoo() {
   int bar_arg1 = 0;
   FuncTemplate<Bar, &Bar::FuncBar>(bar_, bar_arg1);
   //                ^^^^^^^^^^^^^
}

Upvotes: 3

Related Questions