Scott Oliver
Scott Oliver

Reputation: 557

C++: two functions, each takes enum parameter, signatures match?

In the scenario where two functions exist and both accept an enum as a parameter (different enums), can a single type of function pointer refer to them both?

enum MyEnum1 {...};
enum MyEnum2 {...};

void blah( MyEnum1 one );
void guff( MyEnum2 two );

void (*pFunc[2]) ( int );

pFunc[0] = blah;
pFunc[1] = guff;

Is there a better way to do this?

Upvotes: 1

Views: 1463

Answers (2)

ap-osd
ap-osd

Reputation: 2834

Is there a better way to do this?

It really depends on what you are trying to achieve with having one function take 2 kinds of parameters.

C++ overloaded functions support having the same function with different parameters.



    #include "stdio.h"

    enum Enum1
    {
        E1_one,
        E1_two
    };

    enum Enum2
    {
        E2_one,
        E2_two
    };

    class Foo
    {
    public:
        void Bar(Enum1 e1)
        {
            printf("Function parameter Enum1\n");    
        }

        void Bar(Enum2 e2)
        {
            printf("Function parameter Enum2\n");
        }
    };

    int main(int argc, char** argv[])
    {
        Foo foo;
        foo.Bar(E1_one);
        foo.Bar(E2_two);

        return 0;
    }

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249502

No, because the enum types are not implicitly convertible, much less the same exact type. You could easily do what you want by making the functions take an int and cast it to the enum with validation at the top.

Upvotes: 3

Related Questions