使用模板参数定义类的方法 [英] Defining methods of class with template parameters

查看:103
本文介绍了使用模板参数定义类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

档案main2.cpp:

File main2.cpp:

#include "poly2.h"

int main(){
 Poly<int> cze;
 return 0;
}

文件poly2.h:

template <class T>
class Poly {
public:
 Poly();
};

文件poly2.cpp:

File poly2.cpp:

#include "poly2.h"

template<class T>
Poly<T>::Poly() {
}

编译:

src$ g++ poly2.cpp main2.cpp -o poly
/tmp/ccXvKH3H.o: In function `main':
main2.cpp:(.text+0x11): undefined reference to `Poly<int>::Poly()'
collect2: ld returned 1 exit status

我试图编译上面的代码,但在编译期间有错误。应该使用模板参数修复编译构造函数。

I'm trying to compile above code, but there are errors during compilation. What should be fixed to compile constructor with template parameter?

推荐答案

完整的模板代码必须出现在一个文件中。你不能分离多个文件之间的接口和实现,就像你使用普通类一样。为了解决这个问题,许多人将类定义写在头文件中,并在另一个文件中实现,并在头文件的底部包含实现。例如:

The full template code must appear in one file. You cannot separate interface and implementation between multiple files like you would with a normal class. To get around this, many people write the class definition in a header and the implementation in another file, and include the implementation at the bottom of the header file. For example:

Blah.h:

#ifndef BLAH_H
#define BLAH_H

template<typename T>
class Blah {
    void something();
};

#include "Blah.template"

#endif


$ b b

Blah.template:

Blah.template:

template<typename T>
Blah<T>::something() { }

相当于将 Blah.template 的内容复制粘贴到 Blah.h 头中,一切都将在一个文件中,当编译器看到它,并且每个人都很高兴。

And the preprocessor will do the equivalent of a copy-paste of the contents of Blah.template into the Blah.h header, and everything will be in one file by the time the compiler sees it, and everyone's happy.

这篇关于使用模板参数定义类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆