w******g 发帖数: 67 | 1 I have a simple C++template code, but I cannot get it run.
In DataTemplate.h:
template
ElemType* getVecElemPointer(int index, vector& vec);
In DataTemplate.cpp:
template
ElemType* getVecElemPointer(int index, vector& vec)
{
if( (index0) )
{
return &vec[index];
}
return (ElemType*) 0;
}
It is fine when I compile it: "g++ -c -g DataTemplate.cpp"
In another class implementation file: test.cpp
#inclu | y*******g 发帖数: 6599 | 2 都放在头文件中呢?
【在 w******g 的大作中提到】 : I have a simple C++template code, but I cannot get it run. : In DataTemplate.h: : template : ElemType* getVecElemPointer(int index, vector& vec); : In DataTemplate.cpp: : template : ElemType* getVecElemPointer(int index, vector& vec) : { : if( (index0) ) : {
| S*********g 发帖数: 5298 | 3 把cpp里的内容放到hpp里
另外,你这个getVecElemPointer不能返回第一个element啊
【在 w******g 的大作中提到】 : I have a simple C++template code, but I cannot get it run. : In DataTemplate.h: : template : ElemType* getVecElemPointer(int index, vector& vec); : In DataTemplate.cpp: : template : ElemType* getVecElemPointer(int index, vector& vec) : { : if( (index0) ) : {
| w******g 发帖数: 67 | 4 Yes, it works when I put both the declaration and implementation in the head
file, like:
In DataTemplate.h:
template
ElemType* getVecElemPointer(int index, vector& vec)
{
if( (index0) )
{
return &vec[index];
}
return (ElemType*) 0;
}
The linkage works. Can you explain why? Thanks. | w******g 发帖数: 67 | | c*******3 发帖数: 21 | 6 Answer from http://www.cplusplus.com/doc/tutorial/templates.html:
Templates and multiple-file projects
From the point of view of the compiler, templates are not normal functions
or classes. They are
compiled on demand, meaning that the code of a template function is not
compiled until an
instantiation with specific template arguments is required. At that moment,
when an instantiation is
required, the compiler generates a function specifically for those arguments
from the template.
When projects
【在 w******g 的大作中提到】 : I have a simple C++template code, but I cannot get it run. : In DataTemplate.h: : template : ElemType* getVecElemPointer(int index, vector& vec); : In DataTemplate.cpp: : template : ElemType* getVecElemPointer(int index, vector& vec) : { : if( (index0) ) : {
|
|