Search code examples
c++templatesvisual-studio-templates

VS2008 extern templates


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?


Solution

  • 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.