patterncppMinor
Is there a better way to insert an enum into a set without macros?
Viewed 0 times
withoutinsertenumintowaybettermacrosthereset
Problem
I created an
Here is the
and this is the constructor where I add the values
enum for a class and in the constructor I inserted all the enum values into a set. I am wondering if there is a better way anyone can recommend. I feel like there should be, but have been unable to think of one or find one online. I wrote the code in C++ and am using the Boost libraries.Here is the
enum:class CreateAndUseIniFile {
std::set m_modules;
enum iniFileValues {
FIXED_VOLTAGE1,
FIXED_VOLTAGE2,
FIXED_VOLTAGE3,
FIXED_VOLTAGE4
}
}and this is the constructor where I add the values
CreateAndUseIniFile::CreateAndUseIniFile() {
m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE1);
m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE2);
m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE3);
m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE4);
}Solution
You can iterate over the
Note: This will work with your specific case... don't do this if you have
enum and insert each one individually.for ( int i = FIXED_VOLTAGE1; i != FIXED_VOLTAGE4; i++ )
{
m_modules.insert(CreateAndUseIniFile::static_cast(i));
}Note: This will work with your specific case... don't do this if you have
enums with set values that contain gaps between enum values.Code Snippets
for ( int i = FIXED_VOLTAGE1; i != FIXED_VOLTAGE4; i++ )
{
m_modules.insert(CreateAndUseIniFile::static_cast<iniFileValues>(i));
}Context
StackExchange Code Review Q#44158, answer score: 6
Revisions (0)
No revisions yet.