简体   繁体   English

如何使用模板实现发布头文件?

[英]How to publish header files with template implementations?

We are creating a set of libraries with a public API which is to be used by different third parties. 我们正在使用公共API创建一组库,供不同的第三方使用。 Some of the libraries are pure C so obviously they have a C styled header with functions and struct definitions and the corresponding library. 一些库是纯C的,因此显然它们具有C样式的标头,其中包含函数和结构定义以及相应的库。 They are ok. 他们都还好。

Some of the libraries are written with the usage of a moderately complex C++ (targeting older compilers), so there we have implemented some form of the famous pimpl idiom. 一些库是使用中等复杂的C ++(针对较旧的编译器)编写的,因此,我们已经实现了著名的pimpl惯用语的某种形式。 This is ok too. 也可以

On the other end a significant part of the header files is C++ using heavily templated code. 另一方面,头文件的重要部分是使用大量模板化代码的C ++。 Knowing Why can templates only be implemented in the header file? 知道为什么只能在头文件中实现模板吗? but also not willing to disclose too much implementation details to eyes who are not supposed to see them we have heavily refactored them to exclude as much internal details as possible and having only the really necessary bits... and there is still a significant amount of code left. 但又不愿意向不应该看到它们的人透露太多实施细节,我们已经对其进行了重大重构,以排除尽可能多的内部细节,并且只包含真正必要的位...而且仍然有相当多的内容剩下的代码。

So it puzzles me: Is there a preferred way of distributing header files which largely contain templates? 因此,这使我感到困惑:是否存在一种分发主要包含模板的头文件的首选方法? What good practices, best approaches and tips and tricks are there? 有哪些好的做法,最佳方法以及技巧和窍门?

Look at your C++ compiler's header files, for an inspiration. 查看您的C ++编译器的头文件,以获取启发。 The standard C++ library is full of templates, and you will generally find all the template code in the headers. 标准的C ++库充满了模板,通常您会在标头中找到所有模板代码。

Having said that, if particular templates are meant to be used with a small number of possible classes (or values) as template parameters, you do have an option of explicitly instantiating templates inside the library itself, leaving just the bare template declarations visible in the header files. 话虽如此,如果特定模板打算与少量可能的类(或值)一起用作模板参数,则可以选择在库本身内部显式实例化模板,而仅在模板中可见裸模板声明。头文件。

Using a simpler pre-C++11 scenario as an example, a C++ library will typically provide a std::basic_string implementation for only a std::basic_string<char> and std::basic_string<wchar_t> ; 以更简单的C ++ 11之前的场景为例,C ++库通常仅为std::basic_string<char>std::basic_string<wchar_t>提供std::basic_string实现; and leave a bunch of template code inside the library itself, with just a bare std::basic_string template declaration visible in the header files. 并将一堆模板代码留在库本身中,在头文件中仅显示一个裸露的std::basic_string模板声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM