函数模板特化编译错误

编程入门 行业动态 更新时间:2024-10-14 22:14:42
本文介绍了函数模板特化编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
##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屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 06:25:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405469.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特化   函数   模板   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!