Search code examples
c++templatesinheritancefunction-pointersmember-pointers

c++ template and inheritance with method pointer


if I declare:

class Avoidance : public Schema<std_msgs::String,prog1::Command>{

and I try to

    void*(Schema<std_msgs::String,prog1::Command>::*pt)();
    pt=&Avoidance::frontBusy;

compiler report me

error: cannot convert ‘void* (Avoidance::*)()’ 
to 
‘void* (Schema<std_msgs::String_<std::allocator<void> >, prog1::Command_<std::allocator<void> > >::*)()’ in assignment

why? Avoidance inherits from

  Schema<std_msgs::String,prog1::Command>

then Avoidance IS Schema<.....>


Solution

  • Getting rid of templates to simplify, suppose you have

    class B {
    public:
        void f();
    };
    
    class D : public B {
    public:
        void g();
    };
    

    It might seem a little backwards at first, but you can cast void (B::*)() to void (D::*)(), but you cannot cast void (D::*)() to void (B::*)(). This makes sense when you think about how they would later be used.

    void test() {
        void (D::*p)() = &B::f; // OK!
        void (B::*q)() = &D::g; // ERROR!
    
        B b;
        D d;
    
        (d.*p)(); // Calls B::f on `d`.  Okay, `B::f` is an inherited member.
        (b.*q)(); // Calls D::g on `b`?? But that's not a member of `b` at all!
    }