2

I have defined a template function and want to call different specializations according to different input:

// function
template <typename T>
void f() {...}

// specialization 1
template <>
void f<C1>() { ... }

// specialization 2
template <>
void f<C2>() { ... }


// class 
class Cbase {};

class C1 : Cbase {};

class C2 : Cbase {};

int main()
{
    std::string s = input();
    Cbase* c;

    if (s == "c1")
    {
      // here I want to use `specialization 1` but not 
      // call immediately here but later, so I create an instance of C1
      c = new C1;
    }
    else
    {
      // here I want to use `specialization 2` but not
      // call immediately here but later, so I create an instance of C2
     c = new C2;
    }

    // Is there a way to call specializations according to the type of `c`? 
    // Can I get the type in the runtime to call the particular 
    // template specializations I want?
}

Is there a way to call specializations according to c? Can I get the type in the runtime to call the particular template specializations I want?

hliu
  • 1,015
  • 8
  • 16

2 Answers2

4

No. Templates are by definition a compile time construct. If you need runtime polymorphism, then you should basically be looking towards virtual functions.

robthebloke
  • 9,331
  • 9
  • 12
1

Restructure your program to something like:

template <typename T>
void main_function()
{
    T c;

    // f<T>();
    // ...
}

int main()
{
    std::string s = input();

    if (s == "c1")
    {
        main_function<C1>();
    }
    else
    {
        main_function<C2>();
    }
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302