Does the C++ standard say anything about the exact point in time, when the code for the virtual methods of class templates is generated?
Consider the following example:
class Interface
{
public:
virtual void f() = 0;
};
template <unsigned int V>
class A : public Interface
{
public:
virtual void f()
{
}
};
Interface* instantiate()
{
// class template instantiation with argument V=0
return new A<0>();
}
// specialization of f() for template argument V=0
template <> void A<0>::f()
{
cout << "Output from A<0>::f()" << endl;
};
int main()
{
Interface* i = instantiate();
i->f();
return 0;
}
The class template A declares a virtual method f(). In our example the function instantiate() implicitly instantiates the class template A, before any explicitly specialization of A<0>::f() has been done. In the above example, the specialization is done after implicit instantiation of class template A has happened. Now, at least my ARM-Compiler and g++ pick the specialized version of A<0>::f(), i. e. the main() program prints “Output from A<0>::f()” to the screen.
Can I always be sure, that it is sufficient to define the specialization of a virtual method of a class template after this class template has been implicitly instantiated? I would feel better, if the observed behaviour was backed by the C++ standard. I did not find any clear statement about this topic. The closest part would be 14.7.3/6, which is somewhat unspecific when it comes to virtual methods:
If a template, a member template or the member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instan- tiation to take place, in every translation unit in which such a use occurs; no diagnostic is required. If the program does not provide a definition for an explicit specialization and either the specialization is used in a way that would cause an implicit instantiation to take place or the member is a virtual member function, the program is ill-formed, no diagnostic required. An implicit instantiation is never generated for an explicit specialization that is declared but not defined