Hi,
One of my class' member method take as an argument of enumeration type: it produces different side effects for different enum. I was wondering whether it's possible to use template as a lookup table, two possible solutions came up to my mind, but none of them seems to work:
//// 1 ////
class A {
public:
enum AEnum : uint8_t { first, second, ... };
private:
template<AEnum N, typename T>
struct impl {
static void do_sth(T t) { ... };
};
template<typename T>
struct impl<first, T> {
static void do_sth(T t) { ... };
};
public:
template<typename T>
void do_sth(AEnum e, T t) {
impl<e, T>::do_sth(t);
}
}
//// 2 ////
class A {
public:
enum AEnum : uint8_t { first, second, ... };
private:
template<typename T_enum, typename T>
struct impl {
static void do_sth(T t) { ... };
};
template<typename T>
struct impl<uint8_t[2], T> { // A::first
static void do_sth(T t) { ... };
};
public:
template<typename T>
void do_sth(AEnum e, T t) {
impl<uint8_t[static_cast<uint8_t>(e) + 1u], T>::do_sth(t);
}
}
Is it really bad idea to code it this way?
@Oli Charlesworth
What's wrong with a switch statement?
Supported types of do_sth's second argument (T) varies with value of e, e.g. A::first supports integrals, and A::second STL containers, e.g.:
template<typename T>
void do_sth(AEnum e, T t) {
switch(e) {
case first:
std::cout << &t << std::endl;
break;
case second:
std::cout << t.data() << std::endl;
break;
default:
break;
}
A a;
a.do_sth(A::first, 0);