模板类型的c++运行时决策

C++ runtime decision for a template type

本文关键字:运行时 决策 c++ 类型      更新时间:2023-10-16
 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;
 }

在两个块中,我必须执行相同的指令流。例如:

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

如果它们只有两个,我可以写两次,但这是一个有很多条件的可怕的解决方案。是否有一种方法可以在"if-else"之后为选定的类型执行此操作?我不能说会选哪一种?我该怎么办?

可以使用函数模板:

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

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