简体   繁体   中英

Another way to test the value of an enum in C++

In C i can test the value of an enum using if/else statement. For example:

enum Sport {Soccer, Basket};


Sport theSport = Basket;

if(theSport == Soccer)
{
   // Do something knowing that it is Soccer
}
else if(theSport == Basket)
{
   // Do something knowing that it is Basket
}

Is there another way to do this work with C++?

Yes, instead of using if-else statement, you can use virtual functions as part of interfaces.

I make you an example:

class Sport
{
public:
    virtual void ParseSport() = 0;
};

class Soccer : public Sport
{
public: 
    void ParseSport();
}

class Basket : public Sport
{
public:
    void ParseSport();
}

And after use your object in this way:

int main ()
{
    Sport *sport_ptr = new Basket();

    // This will invoke the Basket method (based on the object type..)
    sport_ptr->ParseSport();
}

This is thanks to the fact that C++ adds object oriented features.

You can

1 use template magic at compile time to perform different actions for different and unrelated types;

2 use inheritance and polymorphism at run time to perform different actions on types related by inheritance (as in gliderkite's and rolandXu's answers);

3 use C-style switch statements on enum (or other integer types).

EDIT: (very simple) example using template:

/// class template to be specialised
template<typename> struct __Action;
template<> struct __Action<Soccer> { /// specialisation for Soccer
  static void operator()(const Soccer*);
};
template<> struct __Action<Badminton> { /// specialisation for Badminton
  static void operator()(const Badminton*);
};

/// function template calling class template static member
template<typename Sport> void Action(const Sport*sport)
{
   __Action()(sport);
}

you are still testing the value in C, that is enum value, not the type of theSport. The C++ supports runtime type checking, called RTTI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM