How to Instantiate a Template Class with Parameters at Runtime in C++?

79 views Asked by At

I'm relatively new to C++ and currently facing a challenge with template instantiation where the template parameter needs to be determined at runtime.

Here's a simplified version of my scenario:

But I stuck at this issue.

template <int a>
class ClassA
{
do something with a;
};

int main()
{
  int array[3] = { 2, 2,2};

  for (int i = 0; i < 3; i++)
  {

    ClassA<array[i]> *class_a_instance = new ClassA<array[i]>(constrcutor arguements);
  }
}

I understand that C++ requires non-type template parameters like a in ClassA to be known at compile-time, making ClassA<array[i]> illegal.

However, I'm looking for a workaround for the following constraints:

  • I can't modify ClassA.
  • The values I need to use come from an array or are otherwise only known at runtime.
  • I prefer not to write repetitive code manually for each possible case (e.g., ClassA<1>, ClassA<2>, ClassA<3>, ...).

I cannon modify ClassA directly, which isn't an option for me.

Is there a design pattern, language feature, or coding strategy that could provide a clean solution to this problem?

Thank you in advance & Best regards

1

There are 1 answers

6
Klaus On

The concept of templates is in general a compile time construct.

The simple answer to your question is: You can't instantiate any templates depending on runtime content of variables.