Reputation: 685
I have an enum class defined like so in myClass.h:
enum class SpeedMode {
SPEED_SLOW = 0,
SPEED_NORMAL = 1,
SPEED_FAST = 2
};
In another file I'd like to use my enum as an int:
void myOtherClass::myFunc(const SpeedMode& speed_mode) {
int speed_as_int = speed_mode;
.
.
.
}
In the same file I defined my enum (myClass.h) I try to define an operator override:
int operator= (const SpeedMode& mode) {
return static_cast<int>(mode); //The real logic is more complex and will use a switch statement
}
But I get this error: error: 'int operator=(const SpeedMode&)' must be a nonstatic member function
.
If I try to wrap it in something like struct SpeedModeUtils { }
which allows that file to compile but then myOtherClass gives me this error where I try to make use of the override:
error: cannot convert 'const SpeedMode' to 'int' in initialization
I'm aware I could use the old non-class enum, but this is a large project and I much prefer the type safety of an enum class. I'm also aware I can use static_cast but I'd prefer to avoid that for likely obvious reasons.
If this fails I'll simply use a manual conversion function, but figured this would be a 'nicer' way of handling this.
Upvotes: 0
Views: 823
Reputation: 2198
You need access to the underlying data type of the enum class, meaning the int.
The way to do this is to use std::underlying_type<T>
to access the integer value.
The way you do this is:
#include <type_traits>
auto speed_mode_as_int = static_cast<std::_underlying_type<SpeedMode>::type>(speed_mode);
I made a minimum working example here which should get you started
#include <type_traits>
#include <iostream>
#include <cassert>
enum class SpeedMode {
SPEED_SLOW = 0,
SPEED_NORMAL = 1,
SPEED_FAST = 2
};
bool is_fast(const SpeedMode& speed_mode)
{
auto speed_mode_as_int =
static_cast<std::underlying_type<SpeedMode>::type>(speed_mode);
switch(speed_mode_as_int)
{
case 2:
return true;
default:
return false;
}
}
int main(void) {
auto mode = SpeedMode::SPEED_SLOW;
assert(false == is_fast(mode));
mode = SpeedMode::SPEED_NORMAL;
assert(false == is_fast(mode));
mode = SpeedMode::SPEED_FAST;
assert(true == is_fast(mode));
return 0;
}
I compiled it with the following compile string: clang++ -std=c++17 main.cpp
.
Upvotes: 1
Reputation: 19
As a compiler said you, you can't define such an assignment operator. It said int operator=(const SpeedMode&)' must be a nonstatic member function
, enums just do not have members in C++.
Upvotes: 0