Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an enum within namespace

I am having some problems accessing enums that are wrapped in namespaces.

My issue is that I have two namespaces for two different implementations of an algorithm. The issue is I have two enums for the modes in each namespace, each being slightly different. In one file I want to compare the two implementations. The issue arises that I cannot then use the enums without the two clashing. Can any one describe how I might go about doing this without using namespace

namespace implementation1{
enum modes {mode_standard, mode_special, fast_mode}
}
namespace implementation2{
enum modes {mode_default, mode_repeat, fast_mode}
}

Note this is just an example mine is a bit more complex but it demonstrates what i want to do. I want to try and solve it this way as opposed to refactoring into a global enum or renaming the modes, though that is an option if there is no other way.

like image 870
Dast99 Avatar asked Apr 24 '26 19:04

Dast99


1 Answers

I am not sure what is your problem, but this work ok for you? if not, please elaborate more on the example:

namespace implementation1 {
enum modes { mode_standard, mode_special, fast_mode };
}
namespace implementation2 {
enum modes { mode_default, mode_repeat, fast_mode };
}

int main(int argc, char *argv[]) {
  if (implementation1::fast_mode == implementation2::fast_mode) { // foo mode use...
  }
  return 0;
}

Updating an enum can break your "equivalence":

namespace implementation1 {
enum modes { mode_standard, mode_special, fast_mode };
}
namespace implementation2 {
enum modes { first_mode, mode_default, mode_repeat, fast_mode };
}

int main(int argc, char *argv[]) {
  // foo mode use... this not work now
  if (implementation1::fast_mode == implementation2::fast_mode) {
  }
  return 0;
}

The enum values are automatically assigned, if you need compare the enums from his name you need menage the "assigned value" manually:

namespace implementation1 {
enum modes { mode_standard, mode_special, fast_mode = 3 };
}
namespace implementation2 {
enum modes { first_mode, mode_default, mode_repeat, fast_mode = 3 };
}

but it is error prone, I strongly recommend do not use this, if you need details about this I recommend read about the motivations about the new scoped enums(eg: enum class), available from c++11.

like image 198
Alvaro Denis Acosta Avatar answered Apr 26 '26 09:04

Alvaro Denis Acosta



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!