General switch-case/if-else implementation

Source: Internet
Author: User

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");
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.