I have certain code that I want to optimize. It looks like this:
function abc( string format ) {
if (format == "a") { // this is a string, I shouldn't have used single quote, sorry for the confusion
classx::a t;
doit(t);
}
if (format == "b"){
classx::b t;
doit(t);
}
if (format == "c"){
classx::c t;
doit(t)
}
if (format == "d"){
classx::d t;
doit(t);
}
}
Currently there is many doit() function with different type
function doit( classx:a ) {
different code for a
}
function doit( classx:b ) {
different code for b
}
...etc
As you can see, a lot of code is replicated. However I can't figure out how to reduce the words. Note that : doit(x) has overloaded by different type. a,b,c,d class is derived from a class named "X".
I may create a pointer type classx::X :
classx::X *t;
if (format == "a") t = new classx::a
if (format == "b") t = new classx::b
if (format == "c") t = new classx::c
if (format == "d") t = new classx::d
doit(*t)
but then still need to write a doit() for type classx::X with a bunch of "if then" and cast to the correct type... as C++ can't auto-detect and cast to correct type.
I wonder if there is a faster/smarter way to do this. Thanks in advance.