将仅头模板库编译到共享库中? [英] Compile header-only template library into a shared library?

查看:94
本文介绍了将仅头模板库编译到共享库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在设计一个新的C ++库,并决定采用基于模板的方法,以及一些特定的部分模板专门化的角落情况。特别是,这将是一个标题模板库



现在,有一些担心这会导致很多代码复制,因为这个模板库将被编译到使用它的任何其他共享库或可执行文件(可以说只有那些被使用的部分)。我仍然认为这不是一个问题(特别是,编译器甚至可以内联的事情,它不能跨共享库边界)。



但是,因为我们知道是否有一种方法可以将这个头文件编译成库,并提供一个不同的头文件,只有声明,没有别的东西?注意,库必须包含不仅是通用的实现,而且是部分专业化。

解决方案

是的。您可以做的是使用编译器的显式模板实例化语法显式实例化CPP文件中的模板。以下是如何在VC ++中使用显式实例化: http ://msdn.microsoft.com/en-us/library/by56e477(v = VS.100).aspx 。 G ++具有类似的功能: http://gcc.gnu.org /onlinedocs/gcc/Template-Instantiation.html#Template-Instantiation



请注意,C ++ 11引入了显式实例化的标准语法, [14.7.2] FDIS的显式实例化:


显式实例化的语法是:


显式实例化



extern opt




We are in the process of designing a new C++ library and decided to go with a template-based approach along with some specific partial template specialisations for corner cases. In particular, this will be a header-only template library.

Now, there is some concern that this will lead to a lot of code duplication in the binaries, since this template 'library' will be compiled into any other shared library or executable that uses it (arguably only those parts that are used). I still think that this is not a problem (in particular, the compiler might even inline things which it could not across shared library boundaries).

However, since we know the finite set of types this is going to be used for, is there a way to compile this header into a library, and provide a different header with only the declarations and nothing else? Note that the library must contain not only the generic implementations but also the partial specialisations..

解决方案

Yes. What you can do is explicitly instantiate the templates in CPP files using the compiler's explicit template instantiation syntax. Here is how to use explicit instantiation in VC++: http://msdn.microsoft.com/en-us/library/by56e477(v=VS.100).aspx. G++ has a similar feature: http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html#Template-Instantiation.

Note that C++11 introduced a standard syntax for explicit instantiation, described in [14.7.2] Explicit instantiation of the FDIS:

The syntax for explicit instantiation is:

explicit-instantiation:

externopt template declaration

这篇关于将仅头模板库编译到共享库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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