The following function returns a variable (defined: enum carType { };
).
How could I modify the enum so it can have only 2 posible values: (3 - Minivan, 4 - Sedan)
The function returns the enum value that corresponds to it.
Thank you!
typeApp modif_enum(string type)
{
return carType;
}
CodePudding user response:
In general the range of enum values is not limited by its enumerators. For example 3
is a valid value of
enum foo { a,b };
However, the range is limited by the underlying type and since C 11 you can specify that explicitly. For only two possible values you can use bool
:
enum class carType : bool { MiniVan = 0, Sedan = 1};
// or just enum class carType : bool { MiniVan,Sedan};
carType modif_enum(const std::string& type) {
return static_cast<carType>(type == "Sedan");
}
CodePudding user response:
You can just define the enum values that you want, anything else is not a possible value
You might want to include an Invalid
state for when the conversion does not work, or return a std::optional, or alternatively throw an exception in that case.
enum class typeApp
{
Minivan = 3,
Sedan = 4
};
typeApp modif_enum(string type)
{
if(type == "Minivan") return typeApp::Minivan;
if(type == "Sedan") return typeApp::Sedan;
// maybe return an 'Invalid' value or a std::optional here instead.
throw std::runtime_error("Invalid enum value");
}