user3290180
user3290180

Reputation: 4410

C++ runtime decision for a template type

 template<typename T>
 class A
 { std::vector<T> v;
   .... //other variables
   void op1();
   void op2();
   ... //other operations
 };

 int main()
 {
   string type;
   cout<<"which type do you need?"
   cin>>type;
   if(type=="int")
      A<int> ai;
   else  A<float> af;

   return 0;
 }

In both blocks I must do the same flow of instructions. for example:

 ai.op1();
 ai.op2();
 ...

If they are only two I can write it two times but it is a horrible solution with a lot of conditions. Is there a way to do this once for a chosen type after "if-else"? I can't say which type wil be chosen? How should I do?

Upvotes: 1

Views: 1158

Answers (1)

juanchopanza
juanchopanza

Reputation: 227458

You can use a function template:

template <typename T>
void do_stuff()
{
  A<T> ai;
  ai.op1();
  ai.op2(); 
}

then

int main()
{
   std::string type;
   std::cout << "which type do you need?"
   std::cin >> type;

   type == "int" ? do_stuff<int>() : do_stuff<float>();
}

Upvotes: 10

Related Questions