2016-09-06 42 views
-2

我试图根据类型为T的模板类型运行不同的代码。我有2个班级:MediaCustomer
我有一个模板T和函数add(T type)根据类类型C++运行代码

我希望它能够做的是有效地识别哪个类被传递为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")); 

回答

0

你希望有两个不同的定义add(这就是所谓的 “专业化”):

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

template<>语法对声明您正在专门研究模板函数是必需的。

这是编译时静态类型检查,所以如果你调用add(myPotato)它将无法编译。

+2

只有确切已知类型的模板专门化是没有用的。正如你所看到的,什么都不取决于模板参数,这表明在这种情况下模板语法只是浪费。 – Klaus

6

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

你只可以有:

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

在你的代码中的if() else if()语句的问题是,

allCustomers.push_back(type); 

会给你Media类型编译器错误(假设allCustomersstd::vector<Customer> ),反之亦然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"; 
} 
+0

谢谢。这工作正常! –