Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass anonymous enum as function argument

Tags:

enums

c++11

Is it possible to pass anonymous enum as a function parameter? Something like that:

class Foo
{
    enum
    {
        One,
        Two,
        Three
    };
};

void Function( /* ??? */ e)
{
    switch (e)
    {
        case Foo::One: // do stuff...
        case Foo::Two: // ...
    }
}

Solution attempt:

I was trying to determine what's the type of Foo::One by using auto and checking deduced type:

auto u = Foo::One;

But it turned out to be Foo<anonymous enum> so I can't really use that in code.

like image 775
Avert Avatar asked Apr 27 '26 13:04

Avert


2 Answers

I found a possible solution. Ugly, but works:

void Function(decltype(Foo::One) e) {}
like image 189
Avert Avatar answered Apr 30 '26 09:04

Avert


You could turn the function into a function template like this:

template <class Enum> void Function(Enum e)
{
    switch (e)
    {
        case Foo::One: // do stuff...
        case Foo::Two: // ...
    }
}

It can be instantiated and called via

Function(Foo::One);
like image 35
lubgr Avatar answered Apr 30 '26 08:04

lubgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!