Search code examples
c++stdtypedefstd-function

can you pass in any pointer type or base class into a function typedef


I have this code

class ClassX {};

class ClassY : public ClassX {};
typedef std::function<void (ClassX*)> myCaller;

class Foo {
    Foo()
    {
        createCaller(this, &Foo::bar); //line 22 with the error
    }

    template <typename Class>
    void createCaller(Class *obj, void (Class::*func)(ClassX*))
    {
         myCaller mc = std::bind(func, obj, std::placeholders::_1);;
    }

    void bar(ClassY* x)
    {
        printf("fooBrr");
    }

};

and it works fine till bar takes ClassY that extends ClassX instead of ClassX.

i get the compile time error: main.cpp:22:9: No matching member function for call to 'createCaller'

The question is how would i go about allowing bar to take a parameter of any class that extends ClassX or any class at all? is it even possible?


Solution

  • You can't do it because bar is more restrictive than myCaller. You can go the other way however:

    class ClassX {};
    
    class ClassY : public ClassX {};
    typedef std::function<void (ClassY*)> myCaller;
    
    class Foo {
        Foo()
        {
            createCaller(this, &Foo::bar); //line 22 with the error
        }
    
        template <typename Class>
        void createCaller(Class *obj, void (Class::*func)(ClassX*))
        {
             myCaller mc = std::bind(func, obj, std::placeholders::_1);
        }
    
        void bar(ClassX* x)
        {
            printf("fooBrr");
        }
    
    };
    

    Now bar is less restrictive than myCaller so it can be bound.

    You can also have bar take a ClassX* and dynamic_cast it to a ClassY* and check for NULL.