Re: How to convert string to operator
  Home FAQ Contact Sign in
comp.lang.c++ only
 
Advanced search
POPULAR GROUPS

more...

 Up
Re: How to convert string to operator         

Group: comp.lang.c++ · Group Profile
Author: Dizzy
Date: Jun 12, 2007 03:33

V.R. Marinov wrote:
> On Jun 12, 7:56 am, shsingh gmail.com> wrote:
>> I have a function which takes two operands (char*) and a operator
>> (char*)
>>
>> int myFunc(char* operand1, char* operand2, char* myoperator);
>>
>> Depending upon the operator, i want to do the manipulation on both
>> operands. I dont want to hardcode the operator values or use of switch/
>> if-else statement to determine the operation.
>> Is there any way to solve this problem ??
>
>
> In C++ there are at least two ways to get rid of a switch:
> - Factory design pattern
> - Array of pointers to functions

I will also add the "simple" (yet overlooked) function overloading. Many
people prefer things of the form:
int dostuff(int mode, /*other params*/)
{
switch(mode){
case func1: dofunc1(); break;
case func2: dofunc2(); break;
...
}
}

Even when mode is not runtime decided but compile time decided (like APIs
for opening files and having the READ mode, WRITE mode open flag but
knowing at compile time how you want to open it and having it always called
like "open("file", O_READ)") they write stuff like that. When they can use
overloading to have the compiler determine the function to actually execute
at compile time and also get a compile time error if trying to use an
unknown "mode" (instead of a runtime error). ie do something like:
int dostuff(read_mode_t const&, /*other params*/);
int dostuff(write_mode_t const&, /*other params*/);

And have the caller just write "dostuff(read_mode, params);".

PS: in that example read_mode is a static instance of read_mode_t declared
somewhere; it's irrelevant to what contents read_mode_t has, it only
matters it's type and we (ab)use this to have the compiler overloading
lookup mechanism find the apropriate code at compile time

--
Dizzy
no comments
diggit! del.icio.us! reddit!