Home > Enterprise >  Call a class's function template with function pointers as parameters
Call a class's function template with function pointers as parameters

Time:10-31

I'd want to use a function pointer in my template argument list. I do miss something of B even I am writing int in full main of both A and B. I have a class X.h like so, don't know which one it is now causing the error.

struct X
{
  int fun(int a)
    {
        return a;
    }

    template<typename A, typename B>
    A func(int x, B(*f)(int))
    {
        A i = 10;
        return i   f(x);
    }
};

and I like to use it in main.cpp

int main()
{
    X d;    
    std::cout << d.func<int, int>(10, &X::fun) << "\n";
    return 0;
}

The error is No instance of func matches the argument list...

CodePudding user response:

The problem is that the argument &X::fun is of type int (X::*)(int) while the parameter f is of type int(*)(int) (when B = int) and there is no implicit conversion from the former to the latter and hence the error.

To solve this you can change the parameter f to be of type B(X::*)(int) as shown below. Note that the syntax for making a call using member function pointer is different for making a call to a free function.

With C 17, we can use std::invoke.

struct X
{
  int fun(int a)
    {
        return a;
    }

    template<typename A, typename B>
//------------------vvvv-------------->added this X:: here
    A func(int x, B(X::*f)(int))
    {
        A i = 10;
//-----------------vvvvvvvvvv-------->this is the syntax to call using member function pointer
        return i   (this->*f)(x);

       
       //return std::invoke(f, this, x);  //use std::invoke with C  17
    }
};
int main()
{
    X d;    
    std::cout << d.func<int, int>(10, &X::fun) << "\n"; //works now
    return 0;
}

Working demo

  •  Tags:  
  • c
  • Related