I created an 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<CreateAndUseIniFile::iniFileValues> 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);
}
-
\$\begingroup\$ Like the fellow asking codereview.stackexchange.com/q/35208/32004 it sounds like you might be looking for n3815 to become real. \$\endgroup\$Michael Urman– Michael Urman2014年03月13日 02:17:33 +00:00Commented Mar 13, 2014 at 2:17
2 Answers 2
You can iterate over the enum and insert each one individually.
for ( int i = FIXED_VOLTAGE1; i != FIXED_VOLTAGE4; i++ )
{
m_modules.insert(CreateAndUseIniFile::static_cast<iniFileValues>(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.
-
\$\begingroup\$ Thanks, for some reason I thought I couldn't iterate though an enum \$\endgroup\$Aaron– Aaron2014年03月12日 16:45:32 +00:00Commented Mar 12, 2014 at 16:45
-
\$\begingroup\$ @Aaron No problem.
enumsare basically just fancyints. They should only be iterated through during controlled situations like yours. \$\endgroup\$BenVlodgi– BenVlodgi2014年03月12日 16:53:44 +00:00Commented Mar 12, 2014 at 16:53
As an alternative, you can use Boost Assignment Library. Then you will get something like this:
#include <boost/assign/list_of.hpp>
#include <set>
class CreateAndUseIniFile {
public:
enum iniFileValues {
FIXED_VOLTAGE1,
FIXED_VOLTAGE2,
FIXED_VOLTAGE3,
FIXED_VOLTAGE4
};
CreateAndUseIniFile() {
m_modules =
boost::assign::list_of
(FIXED_VOLTAGE1)
(FIXED_VOLTAGE2)
(FIXED_VOLTAGE2)
(FIXED_VOLTAGE3)
(FIXED_VOLTAGE4);
}
std::set<CreateAndUseIniFile::iniFileValues> m_modules;
};