在 “未定义的引用” 这些都是我的文件:模板函数被报道编译
-------- [c.hpp] --------
#ifndef _C
#define _C
#include<iostream>
class C
{
public:
template<class CARTYPE> void call(CARTYPE& c);
};
#endif
-------- [c.cpp] --------
#include "c.hpp"
template<class CARTYPE> void C::call(CARTYPE& c)
{
//make use of c somewhere here
std::cout<<"Car"<<std::endl;
}
-------- [v.cpp] --------
class Merc
{};
-------- [main.cpp中] --------
#include "c.hpp"
#include "v.cpp"
//#include "c.cpp"
int main()
{
Merc m;
C someCar;
someCar.call(m);
}//main
我能够为所有上述文件名为 “.o” 文件,用命令g ++ -c main.cpp和g ++ -c c.cpp等等。 但是当我尝试连接使用g ++ -o汽车合作main.o沃 的名为“.o”文件,我得到这个错误:
main.o: In function `main':
main.cpp:(.text+0x17): undefined reference to `void C::call<Merc>(Merc&)'
collect2: ld returned 1 exit status
错误消失,当我取消对该行的#include“c.cpp “在main.cpp中,但我觉得用这种方式包含cpp文件可能是不好的做法。我做错了吗?在创建单独的对象文件并链接它们时,是否有更好的方法来迎合模板声明? p.s:我在更复杂的类结构中使用模板函数。这里展示的仅仅是一个小例子,目的是向你展示我面临的错误。
请参阅http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – 2010-10-07 05:18:38
@Pavel:您指出的解决方案是我需要的确切解决方案。谢谢:) – Nav 2010-10-07 06:15:14