为什么C ++模板定义需要在标题中? [英] Why do C++ template definitions need to be in the header?

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

问题描述


可能重复:

例如,当定义模板类时,为什么类方法的实现需要在标题中?为什么它们不能在一个实现文件(cpp / cxx)中?

e.g when defining a template class why do the implementations of the class methods need to be in the header? Why can't they be in a implementation file (cpp/cxx)?

推荐答案

模板类不是类,可用于创建类的模板。当你实例化这样的类,例如。 MyTemplate< int> ,编译器就地创建类。为了创建它,它必须看到所有的模板成员函数(以便它可以使用模板创建实际的成员函数,例如 MyTemplate< int> :: foo()),因此这些模板化的成员函数必须在头中。

A template class is not a class, it's a template that can be used to create a class. When you instantiate such a class, e.g. MyTemplate<int>, the compiler creates the class on the spot. In order to create it, it has to see all the templated member functions (so that it can use the templates to create actual member functions such as MyTemplate<int>::foo() ), and therefore these templated member functions must be in the header.

如果成员不在标题中,编译器将简单地假设它们存在于其他地方,只是从模板函数声明中创建实际的函数声明,链接器错误。

If the members are not in the header, the compiler will simply assume that they exist somewhere else and just create actual function declarations from the templated function declarations, and this gives you linker errors.

export关键字应该解决这个问题,但很少编译器支持它(我只知道Comeau)。

The "export" keyword is supposed to fix this, but few compilers support it (I only know of Comeau).

您还可以显式实例化 MyTemplate< int> - 然后编译器将为 MyTemplate< int& / code>,当它编译包含 MyTemplate 成员函数定义模板的cpp文件时。

You can also explicitly instantiate MyTemplate<int> - then the compiler will create actual member functions for MyTemplate<int> when it compiles the cpp files containing the MyTemplate member function definition templates.

这篇关于为什么C ++模板定义需要在标题中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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