关于模板实例化的几个问题

wswqwps 2007-05-25 01:56:59
1:在c++ primer3 423页说:在显示实例化声明所在的文件中,函数模板的定义必须被给出。

我写了下面的代码:

//model.h
template<class T>
T sum_T(T a,T b){return 0;}

//main.cpp
#include "model.h"

//explicit instantiation declare
template int* sum_T<int*>(int* ,int*);

int main(){return 0;}

模板函数定义在头文件里,按它的说法,int显示实例化出现在main.cpp里,应该会编译错误的,但是编译通过没警告。



2:同样在这页,说:对于给定的函数模板实例,显式实例化声明在一个程序中只能出现一次。我又加上一个other.cpp
//other.cpp
#include "model.h"
template int* sum_T<int*>(int* ,int*);

和main.cpp里的已经重复了,但是编译链接都没有错误。甚至在main.cpp里直接再加上一个template int* sum_T<int*>(int* ,int*);也不会有问题。



3.另外请教一下,template int* sum_T<int*>(int* ,int*);
如果写成

template int* sum_T(int* ,int*);
template int* sum_T<int*>(int*);
template int* sum_T();
template int* sum_T<int*>();
编译都没错误,警告说
no function template defined that matches forced instantiation
这会导致出什么问题么?

...全文
300 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
RISCRISC 2007-06-19
  • 打赏
  • 举报
回复
个人理解是,每个编译单元内只能有一个显示实例化
所谓编译单元就是指源文件,所以,每个源文件里都可以有一个显示实例化
一旦有了显示实例化,那么这个源文件里都是以这个类型来实例化

不知道对不对,如有错误请指正~~~
deng2000 2007-05-25
  • 打赏
  • 举报
回复
我来回答第2个问题吧.答案就是"One-Definition Rule", 详情见<<The C++ Programming Language>>9.2.3节. 我这里摘录其中一段:

Consequently, the rule in the standard that says that there must be a unique definition of a class, template, etc., is phrased in a somewhat more complicated and subtle manner. This rule is commonly referred to as "the onedefinition
rule", the ODR. That is, two definitions of a class, template, or inline function are accepted as examples of the same unique definition if and only if
[1] they appear in different translation units, and
[2] they are token-for-token identical, and
[3] the meanings of those tokens are the same in both translation units.
cmail 2007-05-25
  • 打赏
  • 举报
回复
头文件是在include那句那里展开的

在main.cpp中显式实例化声明时已经可以看到模板定义了
taodm 2007-05-25
  • 打赏
  • 举报
回复
你的理解错了。你还不清楚#include的真实含义。
include差不多就是.h里ctrl_a ctrl_c,到cpp里ctrl_v。
wswqwps 2007-05-25
  • 打赏
  • 举报
回复
他说必须要在实例化的这个文件里....我想大概头文件里是不算的
todototry 2007-05-25
  • 打赏
  • 举报
回复
#include "model.h"
=========
你这个不就是把函数模板的定义给出了嘛
wswqwps 2007-05-25
  • 打赏
  • 举报
回复
刚才试了一下,gcc会直接报错。vc03也太不标准了
taodm 2007-05-25
  • 打赏
  • 举报
回复
我建议你找个devcpp,再编译一下试试,去除掉其中的,再来问剩下的。
wswqwps 2007-05-25
  • 打赏
  • 举报
回复
大侠呢,请给我讲讲,谢谢~~~~~~~~~
wswqwps 2007-05-25
  • 打赏
  • 举报
回复
我用的是vc2003.

64,654

社区成员

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

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