VS2008 外部模板

发布于 2024-10-04 09:43:22 字数 706 浏览 1 评论 0原文

Microsoft 有一个扩展,人们可以通过它声明模板实例化将是外部的;因此,它不会被隐式实例化。至少理论上是这样。我尝试用代码重现该内容,

#include <vector>

class Foo{
    int i;
public:
    virtual ~Foo();
};

extern template class std::vector<Foo>;

这给了我

warning C4231: nonstandard extension used : 'extern' before template 
explicit instantiation

但是,似乎没有发生其他事情:程序继续链接查找,即使我使用push_back(并且dumpbin显示push_back已实例化)。

仅当我声明时

extern template void std::vector<Foo>::push_back(const Foo&);

,我才会收到预期的链接器错误。

那么:如何将整个实例化(所有成员)声明为显式,从而防止隐式实例化?

Microsoft has an extension whereby one can declare that a template instantiation will be external; consequentially, it does not get implicitly instantiated. At least that's the theory. I tried reproducing that with the code

#include <vector>

class Foo{
    int i;
public:
    virtual ~Foo();
};

extern template class std::vector<Foo>;

This gives me

warning C4231: nonstandard extension used : 'extern' before template 
explicit instantiation

However, nothing else seems to happen: the program continues to link find, even though I use push_back (and dumpbin shows that push_back was instantiated).

Only when I declare

extern template void std::vector<Foo>::push_back(const Foo&);

I get an linker error as expected.

So: how can I declare the entire instantiation (all members) as explicit, preventing implicit instantiation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

近箐 2024-10-11 09:43:22

我认为您被扩展文档中的这条注释所困扰:

特化中的 extern 关键字仅适用于在类主体之外定义的成员函数。在类声明中定义的函数被视为内联函数并且始终被实例化。

vector::push_back() (以及大部分或全部 std::vector<> 模板)在类声明中定义。

根据注释的内容,成员函数上的 extern 似乎仍应导致实例化,但对于此扩展的记录不足或指定不足也不会感到惊讶。

我怀疑如果不对每个成员函数执行显式 extern ,您将无法执行您想要的操作。

I think you're being bitten by this note in the docs for the extension:

The extern keyword in the specialization only applies to member functions defined outside of the body of the class. Functions defined inside the class declaration are considered inline functions and are always instantiated.

vector::push_back() (and most or all of the std::vector<> template) is defined inside the class declaration.

Given what the note says, it seems that the extern on the member function should still result in an instantiation, but wouldn't be surprised that this extension is under-documented or under-specified.

I suspect you won't be able to do what you want without doing the explicit extern on each member function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文