在C ++中的模板编程 [英] Template programming in C++

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

问题描述

我在使用C ++中的模板进行编程时遇到麻烦。

I am having trouble getting to grips with programming using templates in C++.

请考虑以下文件。

Ch

#ifndef _C_H
#define    _C_H

template <class T>
class C {
public:
    C();
    virtual ~C();
}
#endif _C_H

C.cpp

#include "C.h"

template <class T>
C<T>::C() {

}

template <class T>
C<T>::~C() {
}



尝试在一个名为main.cpp的文件中实例化C的实例。

I try instantiate an instance of C in a file called main.cpp.

#include "C.h"

int main(int argc, char** argv) {
    C<int> c;
}

我收到以下错误。

main.cpp undefined reference to `C<int>::C()'

然后我运行

g++ -o C.o C.pp
g++ -o main.o main.cpp

但得到错误

main.cpp: undefined reference to `C<int>::C()'
main.cpp: undefined reference to `C<int>::~C()'

我相信这可能是一个明显的错误,但我是一个真正的初学者这将感谢任何帮助。

I am sure this probably an obvious mistake, but I am a real beginner at this so would appreciate any help.

谢谢!

推荐答案

当使用模板时,源代码需要在类型实例化时可用,否则编译器不能检查模板代码是否适用于给定类型。将它分成.cpp和.h文件将无法工作,因为其他.cpp文件只知道.h文件。

When using templates, the source code is required to be available whenever the type is instantiated, because otherwise the compiler can't check that the template code will work for the given types. Dividing it into a .cpp and a .h file won't work, because the other .cpp files only know about the .h file.

你基本上必须把.h文件中的所有内容,或者在实现代码中包含一个额外的文件。

You basically have to put everything in the .h file, or include an extra file with your implementation code.

这篇关于在C ++中的模板编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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