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

use*_*180 1 c++ templates types runtime

 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;
 }
Run Code Online (Sandbox Code Playgroud)

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

 ai.op1();
 ai.op2();
 ...
Run Code Online (Sandbox Code Playgroud)

如果他们只有两个,我可以写两次,但这是一个有很多条件的可怕解决方案.有没有办法在"if-else"之后为所选类型执行此操作一次?我不知道会选择哪种类型?我应该怎么做?

jua*_*nza 10

您可以使用功能模板:

template <typename T>
void do_stuff()
{
  A<T> ai;
  ai.op1();
  ai.op2(); 
}
Run Code Online (Sandbox Code Playgroud)

然后

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

   type == "int" ? do_stuff<int>() : do_stuff<float>();
}
Run Code Online (Sandbox Code Playgroud)

  • @ user3290180好吧,你可以把它拆分成更小的函数.您只需要一个函数模板钩子,它的实现方式取决于您. (2认同)