【问题标题】:How to instantiate c++ template according to runtime input?如何根据运行时输入实例化 c++ 模板?
【发布时间】:2019-06-07 03:53:07
【问题描述】:

我定义了一个模板函数,想根据不同的输入调用不同的特化:

// 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?
}

有没有办法根据 c 调用专业化?我可以在运行时获取类型来调用我想要的特定模板特化吗?

【问题讨论】:

    标签: c++


    【解决方案1】:

    没有。根据定义,模板是编译时构造。如果您需要运行时多态性,那么您基本上应该寻找虚函数。

    【讨论】:

      【解决方案2】:

      将您的程序重组为:

      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>();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2022-11-21
        • 2011-09-23
        • 2014-06-22
        • 2019-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 2012-03-18
        相关资源
        最近更新 更多