Re: Convert case/if's code to Polymorphism code
On 2 Oct, 12:54, Vizcayno <vizcay...@gmail.com> wrote:
On Oct 1, 6:56 pm, Nick Hounsome <nick.houns...@googlemail.com> wrote:
On 1 Oct, 09:26, Vizcayno <vizcay...@gmail.com> wrote:
I have the next C++ code:
if (type == "date_only")
return convert_date(data);
else if (type == "date_time")
return convert_date_time(data);
else if (type == "max_double")
return convert_max_double(data);
else if (type == "amount")
return convert_max_double(data);
else ...
How can I apply polymorphism to this construction? Could you help me
coding my example in "polymorphism mode", please?
Why would you want to?
Where are the classes?
If you just want to avoid the big list of if..else then the clean way
is to use a map.
Assuming that the converter functions are not members then use
std::map<string,void (*converter)(TypeOfData data)>
{ edits: quoted banner removed. please don't quote extraneous material. -mod }
Nick, it sounds very interesting, the entire map would be equivalent
to the declaration of the function and the implementation would
be each one of the functions "declared" in the map. It would also be
easy to maintain.
But, assuming the definition you coded using map, how would you
implement this solution? may you please give me some guidelines about
the way to invoke the functions I defined?
thanks!!
All the functions have to have the same signature.
(This would be true for polymorphism as well because polymorpism is
achieved by overriding a specific method with a specific signature).
Basically, you set up the map with
mymap["date_only"] = convert_date;
mymap["date_time"] = convert_date_time;
....
(probably in an object constructor somewhere)
then use it as:
if( mymap.find(type) != mymap.end() )
{
return mymapp[type](data);
}
else
{
throw "invalid type";
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]