samedi 23 mai 2015

C++: Possible to generate a lookup from string to class type

I would like to do the following: I have a templated class which takes 3 types:

file: util.h

template <typename T1, typename T2, typename T3> TemplatedClass(){
   DoSomething(string p1, string p2, string p3) {
        // Does something.
   }
}

main.cc imports a lot of classes and I need to cycle through a lot of class types.

file: main.cc
# include "util.h"
class Type1;
class Type2;
class Type3;
class Type4;
REGISTER("process1", Type1);
REGISTER("process2", Type2);
REGISTER("process3", Type3);
REGISTER("process4", Type4);

int n = NumRegisteredStrings() // returns 4 (for process1...process4)
for (i=0; i < n-2; i++) {
p1 = FetchStringName(i); 
p2 = FetchStringName(i+1);
p3 = FetchStringName(i+2);
// When i=0, p1, p2, p3 = (process1, process2, process3) and 
// t1, t2, t3 are (Type1, Type2, Type3)
// When i=1, p1, p2, p3 = (process2, process3, process4) and
// t1, t2, t3 are (Type2, Type3, Type4)                      
const auto t1 = FetchTypeFromRegistry(p1); 
const auto t2 = FetchTypeFromRegistry(p2); 
const auto t3 = FetchTypeFromRegistry(p3);

TemplatedClass<t1, t2, t3> DoSomething(p1, p2, p3);
}

It's painful to create too many invocations by hand. I've weakly heard about registries, but don't really know how they work. Is there a good resource with an example to see if I can use that to get this done?

Aucun commentaire:

Enregistrer un commentaire