Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ polymorphism - Auto detect derived type

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.

like image 785
w00d Avatar asked Aug 06 '10 04:08

w00d


2 Answers

One possible approach that reduces the repetition to adding new entries to a function map:

template<class T> void innerAbc() {
    T t;
    doit(t);
}

typedef std::map<std::string, void (*)()> FuncMap;

FuncMap initHandlers() {
    FuncMap m;
    m["a"] = &innerAbc<classx::a>;
    // ... extend here
    return m;
}   

void abc(const std::string& format) {
    static const FuncMap handlers = initHandlers();
    FuncMap::const_iterator it = handlers.find(format);
    if (it != handlers.end()) 
        it->second();
}
like image 94
Georg Fritzsche Avatar answered Sep 30 '22 00:09

Georg Fritzsche


Put the format/constructor pairs into a dictionary. The key is that format string, the value is a function pointer to a static factory method that is essentially just a thin wrapper over the constructor. Besides being easier to maintain, it'll do a hash lookup or binary search, depending on the sort of dictionary/map you use.

like image 31
Steven Sudit Avatar answered Sep 30 '22 00:09

Steven Sudit