【问题标题】:Run Code According to Class type C++根据类类型 C++ 运行代码
【发布时间】:2016-09-06 14:42:54
【问题描述】:

我正在尝试根据模板类型T 传递的类来运行不同的代码。
我有 2 个课程:MediaCustomer
我有一个模板T 和一个函数add(T type)

我希望它能够有效地识别哪个类作为T 传递,并将该类型添加到数组中,如下所示。

template <typename T>
void add(T type){

    if(type = Customer) { // This is pseudo code of what I want it to do

        allCustomers.push_back(type);
        cout << "Added Successfully";

    }

    else if (type = Media){
        allMedia.push_back(type);
        cout << "Added Successfully";
    }
}

这就是我试图通过它的方式:

add(Media("test","test")); 

【问题讨论】:

    标签: c++ oop templates c++11 vector


    【解决方案1】:

    如果您有两种已知类型,则无需将此作为模板。

    您只需:

    void add( Customer c );
    void add( Media m );
    

    【讨论】:

      【解决方案2】:

      代码中if() else if() 语句的问题在于

      allCustomers.push_back(type);
      

      对于Media 类型(假设allCustomersstd::vector&lt;Customer&gt;)将给您一个编译器错误,反之亦然对于Customer 类型和

      allMedia.push_back(type);
      

      您可以简单地使用函数重载来做到这一点:

      void add(const Customer& type){
          allCustomers.push_back(type);
          cout << "Added Successfully";
      
      }
      
      void add(const Media& type){
          allMedia.push_back(type);
          cout << "Added Successfully";
      }
      

      如果您有除CustomerMedia 之外的其他类型的通用模板实现,您也可以使用模板特化:

      template<typename T>
      void add(const T& type){
          anyTypes.push_back(type);
          cout << "Added Successfully";
      
      }
      
      template<>
      void add(const Customer& type){
          allCustomers.push_back(type);
          cout << "Added Successfully";
      
      }
      
      template<>
      void add(const Media& type){
          allMedia.push_back(type);
          cout << "Added Successfully";
      }
      

      【讨论】:

        【解决方案3】:

        您想对add 做出两种不同的定义(这称为“专业化”):

        template<typename T> void add(T);
        template<> void add<Customer>(Customer c) {
            ...
        }
        template<> void add<Media>(Media m) {
            ...
        }
        ...
        

        template&lt;&gt; 语法对于声明您正在特化模板函数是必需的。

        这是在编译时进行静态类型检查的,因此如果您调用add(myPotato),它将无法编译。

        【讨论】:

        • 只针对完全已知类型的模板特化是没有用的。如您所见,没有任何东西取决于模板参数,这表明模板语法在这种情况下只是浪费。
        猜你喜欢
        • 2016-02-06
        • 1970-01-01
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 2018-02-18
        • 2016-07-15
        • 2012-04-06
        • 2017-02-26
        相关资源
        最近更新 更多