user3710760
user3710760

Reputation: 567

How to use enum from another class and file withouot repetitive scoping? c++

I feel like this is an easy question but I don't seem to find the answer myself. I was wondering if there is a way of using the enum in another file, without having to use scoping? e.g. Head.h

namespace h{
class Eye{
 enum class State{
  closed = 0, blinking, open, staring, rolling // etc.
 };
 void print(const State &eye);
};
class Body{
  Eye::State eye;
  Eye::State eyesOpen();

};
}

Head.cpp

namespace h{
 void Eye::print(const State &eye){
  switch(eye){
     case Eye::State::closed: cout << "Closed" << endl;
     case Eye::State::blinking: cout << "Blinking" << endl;
     case Eye::State::open: cout << "Open" << endl;

 }

 bool Body::eyesOpen(){
   return eye == Eye::open;
 }
}

I am using Eye::State about 80+ times in my Body class, so I was wondering if there's a way for me to just state that State is Eye::State rather than having to write it 80 times?

Edit: Eye and Body are two separate classes. It's just that Body uses the Eye object

Upvotes: 0

Views: 60

Answers (1)

Useless
Useless

Reputation: 67772

Don't put a type alias at the top of the namespace unless that's really the logical scope you want.

If you just want to save typing in the Body methods you haven't shown, simply

namespace h{
class Body{
  using State = Eye::State;
  State eye;
  State eyesOpen();
};
}

will work. It seems odd that the eyes are the only organ of this body whose state is important, though. If you really want more organ states later, you can remove the class-level alias and just write

bool Body::eyesOpen() {
  using State = Eye::State;
  return eye == State::open;
}

(which is no improvement at all, but imagine it's applied to the other 80 instances you haven't shown us).

Upvotes: 1

Related Questions