Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
以不同类为参数的模板函数 我一直在得到那个奇怪的编译错误“LNK2019未解析的外部符号”C++。 我想创建一个模板函数,将不同的类作为它的参数。事件和项目是我创建的类 template<typename C> void viewFunction(C customClass, char ch){ if(ch = 'E'){ customClass.printName(); customClass.printPrice(); } else{ customClass.printName(); customClass.printSize(); customClass.printWeight(); } }_C++ - Fatal编程技术网

以不同类为参数的模板函数 我一直在得到那个奇怪的编译错误“LNK2019未解析的外部符号”C++。 我想创建一个模板函数,将不同的类作为它的参数。事件和项目是我创建的类 template<typename C> void viewFunction(C customClass, char ch){ if(ch = 'E'){ customClass.printName(); customClass.printPrice(); } else{ customClass.printName(); customClass.printSize(); customClass.printWeight(); } }

以不同类为参数的模板函数 我一直在得到那个奇怪的编译错误“LNK2019未解析的外部符号”C++。 我想创建一个模板函数,将不同的类作为它的参数。事件和项目是我创建的类 template<typename C> void viewFunction(C customClass, char ch){ if(ch = 'E'){ customClass.printName(); customClass.printPrice(); } else{ customClass.printName(); customClass.printSize(); customClass.printWeight(); } },c++,C++,尽管您向我们展示的代码既不完整也不可编译,但我想我理解您的错误。 您似乎正在使用运行时参数(您的charch)和运行时if语句检查模板中应该编译哪些函数(在编译时) 模板不是反射或动态类型。让函数调用根据传入的类型进行更改的唯一方法是通过函数重载 模板函数的函数重载最终将使用Concepts完成,但在当前标准中使用SFINAE完成 如果只有Event和Item使用此函数,我建议使用具体类型的普通旧函数重载,如下所示 void viewFunction(const Event& custo

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

模板不是反射或动态类型。让函数调用根据传入的类型进行更改的唯一方法是通过函数重载

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

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

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

请张贴真实代码,展示您的问题。这里有大量的输入错误和缺少的参数。此代码肯定会产生大量错误(除了未解决的问题),并确保您将模板实现正确地包含到header.btw中。。您是否使用
char ch
参数来指示第一个参数是什么类型的对象(
customclass
)??如果是,您误解了有关模板的某些内容。@tobi303他也误解了有关赋值运算符的一些内容
If(ch='E')
。如果您想比较是否相等,请使用
==
“模板专门化最终将通过概念来完成”您所说的不是真正的模板专门化,而是基于类型接口的候选集消除。虽然可能有更好的说法。也许我用错了词。。。我猜你对概念的处理实际上是简单的函数重载,但对模板化函数的处理?概念(以其当前形式)本质上是一种基于涉及模板参数的表达式的有效性和类型启用/禁用模板选择的方法。我们目前使用的是SFINAE表达式。谢谢!KABoissonneault@ShaneJA如果复制/粘贴我的代码,请确保printName/printPrice/printSize/printWeight是const限定的,以便可以对const变量调用它们。或者使customClass参数不是常量
void viewFunction(const Event& customClass)
{
    customClass.printName();
    customClass.printPrice();
}
void viewFunction(const Item& customClass)
{
    customClass.printName();
    customClass.printSize();
    customClass.printWeight();
}