This is what I would like to do:
ExampleTemplate* pointer_to_template;
cin >> number;
switch (number) {
case 1:
pointer_to_template = new ExampleTemplate<int>();
break;
case 2:
pointer_to_template = new ExampleTemplate<double>();
break;
}
pointer_to_template->doStuff();
This doesn’t compile because the template type must be specified when declaring the pointer. (ExampleTemplate* pointer_to_template should be ExampleTemplate<int>* pointer_to_template.) Unfortunately, I don’t know the type of the template until it’s declared in the switch block. What is the best work around for this situation?
You can’t.
ExampleTemplate<int>andExampleTemplate<double>are two different, unrelated types. If you always have a switch over several options, useboost::variantinstead.Another way is to use an ordinary base class with virtual public interface, but I’d prefer
variant.