0

Is there a way construct an instance of a variadic templated class, where the arguments are only known at run time?

For example,

template <typename... T>
class Example {
  Example(T... args){ // some initialization}
}

int main(){

  // say i only can find out the type of class Example at run time.
  // in the below case it happens to be <int,int,char>
  example = make_unique<Example<int,int,char>>(1,2,'a');
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
prostock
  • 9,327
  • 19
  • 70
  • 118
  • 4
    Template parameters must be known at compile time. If you don't know a type until runtime, you need a factory pattern to decide how to create instances of templates of specific types – Remy Lebeau Sep 04 '19 at 06:33
  • 1
    You are looking for *type erasure*. See [Type erasure techniques](https://stackoverflow.com/questions/5450159/type-erasure-techniques) – L. F. Sep 04 '19 at 09:51
  • Could you provide an example of why you can know the type only at runtime? – mfnx Sep 04 '19 at 09:57

1 Answers1

1

Templates are resolved at compile time. The compiler creates functions with the necessary types. Templates are just a way for programmers to not ending in overloading functions for every possible way.

Btw the compiler exactly knows the datatypes of your example class.

gkhaos
  • 694
  • 9
  • 20