chain ro
chain ro

Reputation: 765

Instantiate a template class at run time in terms of different types

The program is organized as follow:

  1. First it reads a files where the type information is contained.

  2. It has to instantiate a class according to that type.

For instance, if type = float, I have to instantiate an object A<float> a.

Currently I handle this work by plain if-else statements.

if (type == "float") {
    A<float> a;
}

I am wondering if there are some ways to handle a type just like a variable or something else, which let me create the object by A<specific_type> a without judgement?

Upvotes: 1

Views: 1587

Answers (3)

jrsmolley
jrsmolley

Reputation: 419

This doesn't answer your question directly (why do you need to instantiate a templated class at runtime?) but here's one possibility...

If there are too many different types of classes, and if you have control of the format of data file, you could consider using something like XML (https://en.wikipedia.org/wiki/XML). There should be XML libraries available for c++ that would allow you to load file data of any kind of complex structure, manipulate it in c++, then save it back to a file. There would be a small performance hit but for most applications this wouldn't be noticeable.

Upvotes: 0

marom
marom

Reputation: 5230

Are you asking for something like this?

template <class A>
void workWithA(void)
{ 
   A a ;
}

std::map<std::string, void (*f_ptr)(void)> functions ;

functions["float"] = &workWithA<float> ;
functions["int"] = &workWithA<int> ;
...

then you can write

std::string type ;
auto it = functions.find(type) ;
if (it != functions.end())
     it->second() ;

Upvotes: 1

dkg
dkg

Reputation: 1775

You can't instantiate template with parameters changing at runtime.

Templates are processed when compiled. How your program would deal with it if it doesn't know what it is manipulating ?

There still could be a solution if you embark a tool chain with your program that generate a lib from your file that you could use... But I don't know if that is worth the effort.

Upvotes: 1

Related Questions