Search code examples
c++function-pointersc++11method-signature

Array of functions with different signatures


I have this classes:

class Foo
{
    ...
};

class Foo1 : public Foo
{
    ...
};

...

class FooN : public Foo
{
    ...
};

Is it possible to have an array of functions with these kind of signatures:

void f1(Foo1*){}
...
void fN(FooN*){}

Is there any change if these functions are non static member functions instead of regular functions? I don't think this will change something.

Thanks!


Solution

  • I found this workaround for this problem:

    #include <iostream>
    #include <vector>
    
    class Foo
    {
    };
    
    class Foo1 : public Foo
    {
    };
    
    class Foo2 : public Foo
    {
    };
    
    class Foo3 : public Foo
    {
    };
    
    
    void f1(Foo1*)
    {
        std::cout<<"f1\n";
    }
    
    void f2(Foo2*)
    {
        std::cout<<"f2\n";
    }
    
    void f3(Foo3*)
    {
        std::cout<<"f3\n";
    }
    
    template<typename T>
    void AddPointer(std::vector<typename void (*)(Foo*)>& fPointers, T function)
    {
        fPointers.push_back(reinterpret_cast<void (*)(Foo*)>(function));
    }
    
    void main()
    {
        std::vector<typename void (*)(Foo*)> fPointers;
    
        AddPointer(fPointers, f1);
        AddPointer(fPointers, f2);
        AddPointer(fPointers, f3);
    
        Foo1 foo1;
        Foo2 foo2;
        Foo3 foo3;
    
        fPointers[0](&foo1);
        fPointers[1](&foo2);
        fPointers[2](&foo3);
    }