static const std::array in class
I have a templated struct with some enumerations in it and I'd like to make a std::array with the enumerations in it for convenience. Is there any way of doing th开发者_JAVA百科e following?
template< typename A >
struct someClass{
enum class State{
sA,
sB,
sC
}
static const std::array<State,4> the_states = {{
State::sA,
State::sB,
State::sC
}};
};
No. Only static const integral data members can be initialized within a class.
However, you could do this...
template< typename A >
struct someClass
{
enum State
{
sA,
sB,
sC
};
static const std::array<const State,4> the_states;
};
template<typename A>
const std::array<const someClass::State,4> someClass<A>::the_states =
{
someClass::State::sA,
someClass::State::sB,
someClass::State::sC
};
#include <iostream>
#include <array>
template< typename A >
struct someClass{
enum class State {
sA,
sB,
sC
};
static const std::array<State,3> the_states;
};
template<typename A>
const std::array<typename someClass<A>::State,3> someClass<A>::the_states = {
someClass<A>::State::sA,
someClass<A>::State::sB,
someClass<A>::State::sC
};
int main() {
for( auto i : someClass<int>::the_states) {
switch(i) {
case someClass<int>::State::sA:
std::cout << "sA" << std::endl;
break;
case someClass<int>::State::sB:
std::cout << "sB" << std::endl;
break;
case someClass<int>::State::sC:
std::cout << "sC" << std::endl;
break;
}
}
}
note that you can't terminate the list with 0 the way you were trying with the 4 element array, because 0 cannot be converted to an enum class State.
Bah, and in the time it took me to edit my answer with the real answer Dave got it.
精彩评论