I
int2str
All,
What is a good way to replace a simple switch() statement that relies
on #define'ed magic numbers, with a mechanism that can work with
variable values?
Consider the following code:
#include <iostream>
#define FUNC_1 1000
unsigned GetInt()
{
return 3000;
}
const unsigned FUNC_2 = GetInt();
class Test
{
public:
void Func1()
{
std::cout << "Test::Func1()\n";
}
void Func2()
{
std::cout << "Test::Func2()\n";
}
void Dispatch( unsigned func )
{
switch ( func )
{
case FUNC_1:
Func1();
break;
case FUNC_2: // <-- ERROR!
/*
* switch.cpp:33: error: `FUNC_2' cannot
* appear in a constant-expression
*/
Func2();
break;
}
}
};
int main()
{
Test t;
t.Dispatch( FUNC_1 );
t.Dispatch( FUNC_2 );
}
I've tried a multitude of designs I could come up with to solve this
problem, but non seem elegant or portable when it comes to derived
classes etc. For example, I've tried a std::map with pointers to
member functions, which I liked, but I had trouble making that worked
for derived classes since I needed some template "magic" to get the
function pointers for any given class to work.
Lots of if/else would of course work, but that looks ugly as sin and
can get very, very repetitive, especially when there's a lot of
functions to dispatch.
So what would be a good design that can be applied cleanly to classes
of various level of inheritance?
Thanks,
Andre
What is a good way to replace a simple switch() statement that relies
on #define'ed magic numbers, with a mechanism that can work with
variable values?
Consider the following code:
#include <iostream>
#define FUNC_1 1000
unsigned GetInt()
{
return 3000;
}
const unsigned FUNC_2 = GetInt();
class Test
{
public:
void Func1()
{
std::cout << "Test::Func1()\n";
}
void Func2()
{
std::cout << "Test::Func2()\n";
}
void Dispatch( unsigned func )
{
switch ( func )
{
case FUNC_1:
Func1();
break;
case FUNC_2: // <-- ERROR!
/*
* switch.cpp:33: error: `FUNC_2' cannot
* appear in a constant-expression
*/
Func2();
break;
}
}
};
int main()
{
Test t;
t.Dispatch( FUNC_1 );
t.Dispatch( FUNC_2 );
}
I've tried a multitude of designs I could come up with to solve this
problem, but non seem elegant or portable when it comes to derived
classes etc. For example, I've tried a std::map with pointers to
member functions, which I liked, but I had trouble making that worked
for derived classes since I needed some template "magic" to get the
function pointers for any given class to work.
Lots of if/else would of course work, but that looks ugly as sin and
can get very, very repetitive, especially when there's a lot of
functions to dispatch.
So what would be a good design that can be applied cleanly to classes
of various level of inheritance?
Thanks,
Andre