函数模板特化编译错误 [英] function template specialization compile error

查看:37
本文介绍了函数模板特化编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

##A.hh

template<class T> void func(T t) {}
template<> void func<int>(int t) {}

void func2();

##A.cpp

void func2() {}

##main.cpp

func("hello");
func(int());

我得到的错误是:error LNK2005: "void __cdecl func(int)" (??$func@H@@YAXH@Z) 已经在 A.obj 中定义,找到一个或多个多重定义的符号

The error I get is: error LNK2005: "void __cdecl func(int)" (??$func@H@@YAXH@Z) already defined in A.obj, one or more multiply defined symbols found

函数模板特化是否不被视为普通函数模板?看起来它会在 A 的目标文件中.

Is a function template specialization not treated as a normal function template? It looks like it will be in the objective file for A.

推荐答案

As template<>void func<int>(int t) {} 是函数重载而不是函数模板(即所有类型在定义点都是已知的,因此它不再是模板),它必须标记为inline 或在 .cpp 文件中定义以避免多个定义错误,就像任何其他函数定义一样.

As template<> void func<int>(int t) {} is a function overload rather than a function template (i.e., all types are known at the point of definition so it is no longer a template), it must be marked as inline or defined in a .cpp file to avoid multiple definition errors, just as with any other function definition.

这篇关于函数模板特化编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆