函数模板特化在头文件声明而在源文件定义为何出现了重定义错误?

春起之苗 2013-01-23 03:47:41
template.h文件中代码

#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <string>
using namespace std ;

template<typename T>
int Compare( const T & Obj1, const T &Obj2 ) ;//函数模板声明

template<>
int Compare<const char*>(const char* const& , const char* const&) ;//函数模板特化

#include "template.cpp"

#endif

template.cpp文件中代码
#ifndef TEMPLATE_CPP
#define TEMPLATE_CPP
#include <string>
#include "template.h"

using namespace std ;
//函数模板定义
template<typename T>
int Compare( const T &Obj1 , const T &Obj2 )
{
if( Obj1 < Obj2 ) return -1 ;
if( Obj2 < Obj1 ) return 1 ;
return 0 ;
}
//函数模板特化定义
template<>
int Compare<const char*>( const char* const &Obj1 , const char* const &Obj2 )
{
return strcmp( Obj1 , Obj2 ) ;
}

#endif
以上是关于模板特化的声明和定义,但是我在链接的时候出现了重定义错误:
1>LINK : 没有找到 E:\Administrator\Program Design\pieces\Primer cpp\a\Debug\a.exe 或上一个增量链接没有生成它;正在执行完全链接
1>template.obj : error LNK2005: "int __cdecl Compare<char const *>(char const * const &,char const * const &)" (??$Compare@PBD@@YAHABQBD0@Z) 已经在 main.obj 中定义
1>E:\Administrator\Program Design\pieces\Primer cpp\a\Debug\a.exe : fatal error LNK1169: 找到一个或多个多重定义的符号
1>生成日志保存在“file://e:\Administrator\Program Design\pieces\Primer cpp\a\a\Debug\BuildLog.htm”
1>a - 2 个错误,0 个警告
========== 全部重新生成: 成功 0 个,失败 1 个,跳过 0 个 ==========

后来我将函数模板特化的定义放在头文件里面并且将template.cpp文件中的#include<template.h>注释掉就行了,请教各位高手帮忙分析里面的原因!
...全文
562 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
春起之苗 2013-01-23
  • 打赏
  • 举报
回复
回复于: 2013-01-23 16:16:37 template.cpp文件中代码还是不要 #include "template.h" 包含.h头文件这是按照写模板类的定义时在cpp文件中必须包含头文件这个习惯来的, 可是即使我将#include"template.h"注释掉,而函数特化模板的定义仍然放在.cpp文件中依然会出现重定义错误?但是当我将特化模板和模板的定义均放在头文件时就不会有这种错误,我不明白的是我将这两个定义均放在一个cpp文件中,而根据模板编译全包含的方法在头文件末尾添加include就出现了重定义错误,这种方法与定义均放在头文件中有什么不同吗? 我想知道的是这其中原因
逍遥子_ 2013-01-23
  • 打赏
  • 举报
回复
目前模板函数不支持分离编译,具体可以参考一下: http://blog.csdn.net/hjx_1000/article/details/8093701 简单而言,就是编译的时候会为每个cpp文件及其头文件编译成一个目标文件,如果你把模板函数放在cpp文件中,编译阶段,编译器不知道该为你的模板函数或模板类生成那种类型的具体类型,因此也无法生成目标文件。
mymtom 2013-01-23
  • 打赏
  • 举报
回复
template.cpp文件中代码还是不要 #include "template.h"
mymtom 2013-01-23
  • 打赏
  • 举报
回复
模板特化也是一种模板定义,在不支持模板分离编译的情况下,模板定义要放在头文件里的!
lee_鹿游原 2013-01-23
  • 打赏
  • 举报
回复

#ifndef TEMPLATE_CPP
#define TEMPLATE_CPP
#include <string>
#include "template.h"
using namespace std ;
//函数模板定义
template<typename T>
int Compare( const T &Obj1 , const T &Obj2 )
{
	if( Obj1 < Obj2 ) return -1 ;
	if( Obj2 < Obj1 ) return 1 ;
	return 0 ;
}
template<>
int Compare( const char* const &Obj1 , const char* const &Obj2 )
{
	return strcmp( Obj1 , Obj2 ) ;
}
#endif

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧