After a long time in the communication industry, I often find thatProgramIf .. else .. this nesting layer is quite deep in switch writing, so I was born with the idea of writing a general switcher, which isolates this strong coupling writing method, so I used the following implementation.
/*************************************** ******
* General Selector
* 1. Adapt to the original function pointer
* 2. Adapt to the member function pointer
* 3. Adapt to the imitation Function
* 4. Bind a function
**************************************** ****/
Template <typename result,
Typename key,
Typename para>
Class switcher
{
PRIVATE:
Typedef boost: function <result, para> functor;
Public:
Void add_observer (Key key, functor func)
{
Functorset. insert (make_pair (Key, func ));
}
Result match (Key key, Para)
{
Map <key, functor >:: const_iterator ITER;
Iter = functorset. Find (key );
If (ITER! = Functorset. End ())
{
Static_cast <functor> (ITER-> Second) (Para );
}
}
PRIVATE:
Map <key, functor> functorset;
};
Bool some_function (const STD: string & S)
{
STD: cout <S <"this is really neat/N ";
Return true;
}
Class some_class
{
Public:
Bool some_function (const STD: string & S)
{
STD: cout <S <"this is also quite nice/N ";
Return true;
}
};
Class some_function_object
{
Public:
Bool operator () (const STD: string & S)
{
STD: cout <S <
"This shoshould work, too, in a flexible solution/N ";
Return true;
}
};
Switcher <bool, Int, string> myswitcher;
Bool test (INT number, string info)
{
Return myswitcher. Match (number, Info );
}
int main (INT argv, char ** argc)
{< br> function1 F1 (& some_function );
function1 F2 (& some_class: some_function, & S);
function1 F3 (boost: BIND (& some_class: some_function, & S, _ 1);
some_function_object FSO;
function1 F4 (FSO);
myswitcher. add_observer (0, F1);
myswitcher. add_observer (1, F2);
myswitcher. add_observer (2, F3);
myswitcher. add_observer (3, F4);
test (0, "call by F1");
}