c++classtemplatesc++17pointer-to-member

How to pass non-static member function as template argument to another member function?


I want to do something like this:

struct S
{
   void mf() {};

   template <auto f>
   void func()
   {
      f();
   }
};

int main()
{
   S x;
   x.func<x.mf>();
}

However, these are the errors:

error: no matching function for call to 'S::func<x.S::mf>()'`
note: candidate: 'template<auto f> void S::func()'
note:   template argument deduction/substitution failed:
error: could not convert 'x.S::mf' from '<unresolved overloaded function type>' to 'void (S::*)()'

I am not sure I understand what I am doing wrong.

Why is x.mf not resolved since I already instantiated x? And how do I make this work?


Solution

  • Calling member functions through a pointer can be so tricky.

    You want to pass a member function pointer to S::mf like so:

    struct S
    {
        void mf () {std::cout << "called mf\n";};
    
        template <auto f>
        void func ()
        {
            (this->*f)(); 
        }
    };
    
    int main()
    {
        S x;
        x.func<&S::mf>();
    }