模板分布在多个文件中 [英] Templates spread across multiple files

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

问题描述

当在多个文件中声明模板时,C ++似乎很累人。更具体地说,当使用模板类时,链接器需要在单个编译器目标文件中的类的所有方法定义。当你考虑头,其他声明,继承等,事情变得很杂乱。

C++ seems to be rather grouchy when declaring templates across multiple files. More specifically, when working with templated classes, the linker expect all method definitions for the class in a single compiler object file. When you take into account headers, other declarations, inheritance, etc., things get really messy.

在多个文件中组织或重新分配模板成员定义时,是否有任何一般建议或解决方法?

Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files?

推荐答案


在多个文件中组织或重新分配模板成员定义时,是否有任何一般建议或解决方法?

Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files?

是的;不要。

C ++规范允许编译器能够查看整个模板(声明定义)的实例化,并且(由于任何实现的复杂性)大多数编译器保留这个要求。结果是#include的任何模板头也必须#include任何和所有源实例化模板。

The C++ spec permits a compiler to be able to "see" the entire template (declaration and definition) at the point of instantiation, and (due to the complexities of any implementation) most compilers retain this requirement. The upshot is that #inclusion of any template header must also #include any and all source required to instantiate the template.

处理这个的最简单的方法是转储一切

The easiest way to deal with this is to dump everything into the header, inline where posible, out-of-line where necessary.

如果你真的认为这是一个不可接受的侮辱,一个常见的选择是将模板拆分成通常的头/实现对,然后#include在头尾的实现文件。

If you really regard this as an unacceptable affront, a common option is to split the template into the usual header/implementation pair, and then #include the implementation file at the end of the header.

C ++的导出功能可能提供或不提供另一种解决方法。该特征支持不良,定义不明确;虽然它原则上应允许对模板进行某种单独的编译,但它并不一定避免了编译器能够看到整个模板主体的需求。

C++'s "export" feature may or may not provide another workaround. The feature is poorly supported and poorly defined; although it in principle should permit some kind of separate compilation of templates, it doesn't necessarily obviate the demand that the compiler be able to see the entire template body.

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

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