首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-02-11 
关于模板实例化的几个问题1:在c++primer3423页说:在显示实例化声明所在的文件中,函数模板的定义必须被给出

关于模板实例化的几个问题
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
这会导致出什么问题么?



[解决办法]
我建议你找个devcpp,再编译一下试试,去除掉其中的,再来问剩下的。
[解决办法]
#include "model.h "
=========
你这个不就是把函数模板的定义给出了嘛
[解决办法]
你的理解错了。你还不清楚#include的真实含义。
include差不多就是.h里ctrl_a ctrl_c,到cpp里ctrl_v。
[解决办法]
头文件是在include那句那里展开的

在main.cpp中显式实例化声明时已经可以看到模板定义了
[解决办法]
我来回答第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.

热点排行