模板函数以不同的类作为参数

时间:2015-07-03 13:14:43

标签: c++

我一直得到那个奇怪的编译错误" LNK2019未解析的外部符号" C ++。 我想创建一个模板函数,它将使用不同的类作为它的参数。 Event和Items是我创建的类。

template<typename C>
void viewFunction(C customClass, char ch){
   if(ch = 'E'){
       customClass.printName();
       customClass.printPrice();
   }
   else{
       customClass.printName();
       customClass.printSize();
       customClass.printWeight();
   }
}

现在我在main中调用了该函数。我想,当我尝试传递一个类作为我的模板类型时会发生错误。

int main{

Event myEvent1;
Event myEvent2;

Item myItem1;
Item myItem2;

viewFunction(myEvent1, 'E');

viewFunction(myItem1, 'I');

viewFunctionmyEvent2, 'E');

viewFunction(myItem2, 'I');

return 0;
}

1 个答案:

答案 0 :(得分:1)

尽管您向我们展示的代码不完整也无法编译,但我认为我理解您的错误。 您似乎使用运行时 ch语句检查运行时参数(您的char if),该语句应在模板中编译函数(在编译时)。

模板不是反射或动态类型。根据传入的类型,函数调用的唯一变化方法是通过函数重载。

模板函数的函数重载最终将使用Concepts完成,但在当前标准中使用SFINAE完成。

如果只有EventItem使用此函数,我建议使用具体类型的普通旧函数重载,如下所示。

void viewFunction(const Event& customClass)
{
    customClass.printName();
    customClass.printPrice();
}
void viewFunction(const Item& customClass)
{
    customClass.printName();
    customClass.printSize();
    customClass.printWeight();
}