Background
C++11 initializer lists can be used to initialize vectors and arrays with argument passing to constructors.
I have a piece of code below where I would like to initialize such an array with all the enumerations of eCOLORS
from eCOLORS::First
to eCOLORS::Last
using initializer lists.
Original Code
Since all information is known at compile time, I think there is a way to solve this problem.
enum class eCOLORS
{
kBLUE=0, kGREEN, kRED, kPURPLE,
First=kBLUE, Last=kPURPLE
};
template< typename E >
size_t Size()
{
return (size_t)(E::Last) - (size_t)(E::First) + 1;
}
struct Foo
{
Foo( eCOLORS color ) { }
};
int main(int argc, char** argv)
{
Foo a[2] = {
{ eCOLORS::kRED },
{ eCOLORS::kGREEN }
}; // works, but requires manual maintenance if I add another color
/* how to feed v with all the enums from First to Last
without hard-coding?
Foo v[Size<eCOLORS>()] = {
};
*/
}
Ugly Pseudo-Answer
The consensus appears to be that there is currently no way to this.
My original intent in asking this question is, I want to automagically create an array of Foo objects whose initialization is solely based on the enumeration of
eColors
. I wanted a no maintenance solution that would work even after you add more entries intoeColors
.
Using the Enum class from this earlier post, I can write a function template that gives me the functionality that I need. Even without using that Enum class, you could still loop from eCOLORS::First
to eCOLORS::Last
, along with some ugly casts.
My ugly pseudo-answer is kludgy (nowhere as nice as a compile-time initializer list), but at least it is zero maintenance.
NOTE: if better solutions come up, I will update the OP accordingly.
template <typename T, typename E>
std::vector< T >
Initialize_With_Enums()
{
std::vector< T > v;
for( auto p : Enum<E>() )
v.push_back( T( p ));
return v;
}
int main( int argc, char** argv )
{
auto w = Initialize_With_Enum<Foo,eCOLORS>();
}