Home > Net >  Calling a method from an other class using a method pointer
Calling a method from an other class using a method pointer

Time:10-14

I'm passing a method pointer to a function template. It works for some method pointers, but not others.

I tried to help the compiler to differentiate types (declared args vs. passed args) using the tricky my_type_identity (thank to Jarod42) but I fails too.

Here is that minimal code that exposes the problem:

template<class T> struct my_type_identity { using type = T ;};

struct Spam
    {
    };

struct Eggs
    {
    void f0 ( Spam )         {}
    void f1 ( const Spam & ) {}
    };

template <class C> struct Bread
    {
    C c ;
    template <class F,class T> void apply1 ( void (F::*f)( T ), T t )                   { (c.*f)(t) ; }
    template <class F,class T> void apply2 ( void (F::*f)( T ), my_type_identity<T> t ) { (c.*f)(t) ; }
    };

int main ()
    {
    Spam  s ;
    Bread<Eggs> b ;
    b.apply1( &Eggs::f0,s ) ;
    b.apply1( &Eggs::f1,s ) ;  // error
    b.apply2( &Eggs::f0,s ) ;  // error
    b.apply2( &Eggs::f1,s ) ;  // error
    }

CodePudding user response:

In

template <class F,class T>
void apply ( void (F::*f)(T) , T t )

T might be deduced from both parameters, and should be identical. It is not your case.

You might change to

template <class F,class T>
void apply ( void (F::*f)(T) , std::type_identity_t<T> t )

to only deduce from first parameter.

CodePudding user response:

Finally the solution suggested by Useless (not so useless ;-) seems to be good for me.

I distinguish the declared parameters from the actually passed parameters.
See T1 and T2 in the declaration of the method apply :

struct Spam
    {
    };

struct Eggs
    {
    void f0 ( Spam )         {}
    void f1 ( const Spam & ) {}
    };

template <class C> struct Bread
    {
    C c ;
    template <class F,class T1,class T2> void apply ( void (F::*f)( T1 ), T2 t )  { (c.*f)(t) ;}
    };

int main ()
    {
    Spam  s ;
    Bread<Eggs> b ;
    b.apply( &Eggs::f0,s ) ;
    b.apply( &Eggs::f1,s ) ;
    }

Thanx you all!

  • Related