gpt4 book ai didi

c++ - 如何使用外部模板

转载 作者:IT老高 更新时间:2023-10-28 13:01:35 25 4
gpt4 key购买 nike

我一直在浏览 C++0x 的 N3291 工作草案。我对外部模板很好奇。第 14.7.3 节指出:

Except for inline functions and class template specializations, explicit instantiation declarations have the effect of suppressing the implicit instantiation of the entity to which they refer.

仅供引用:术语“显式实例化声明”是 extern template 的标准说法。 .这是在第 14.7.2 节中定义的。

这听起来像是在说如果你使用 extern template std::vector<int> , 然后做任何通常会隐式实例化 std::vector<int> 的事情不会这样做。

下一段更有趣:

If an entity is the subject of both an explicit instantiation declaration and an explicit instantiation definition in the same translation unit, the definition shall follow the declaration. An entity that is the subject of an explicit instantiation declaration and that is also used in a way that would otherwise cause an implicit instantiation (14.7.1) in the translation unit shall be the subject of an explicit instantiation definition somewhere in the program; otherwise the program is ill-formed, no diagnostic required.

仅供引用:术语“显式实例化定义”是这些事情的标准说法:template std::vector<int> .也就是说,没有 extern .

对我来说,这两件事说明了extern template阻止隐式实例化,但它确实阻止显式实例化。所以如果你这样做:

extern template std::vector<int>;
template std::vector<int>;

第二行有效地否定了第一行,明确地执行了第一行隐式阻止发生的事情。

问题是这样的:Visual Studio 2008 似乎不同意。我想使用的方式extern template是为了防止用户隐式实例化某些常用模板,以便我可以在 .cpp 文件中显式实例化它们以减少编译时间。模板只会被实例化一次。

问题是我必须在 VS2008 中围绕它们进行基本的#ifdef。因为如果单个翻译单元看到 extern和非extern版本,它将使 extern版本获胜,没有人会实例化它。然后是链接器错误。

所以,我的问题是:

  1. 根据 C++0x 的正确行为是什么?应该 extern template是否阻止显式实例化?
  2. 如果上一个问题的答案是不应该,那么 VS2008 就出错了(当然,它早在规范之前就已经写好了,所以这不是他们的错)。 VS2010如何处理这个?它是否实现了正确的 extern template行为?

最佳答案

它说

Except for ...class template specializations

所以它不适用于 std::vector<int> ,但是对于它的成员(不是内联成员函数并且可能不是嵌套类的成员。不幸的是,没有一个术语可以同时捕捉“类模板特化和类模板成员类的特化”。所以有些地方只使用前者,但意味着也包括后者)。所以std::vector<int>如果需要,它的嵌套类(如 std::vector<int>::iterator ,如果它被定义为嵌套类)仍将被隐式实例化。

关于c++ - 如何使用外部模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6870885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com