I would like to have a better understanding of when the compiler will implicitly instantiate a member function template.
Consider the following example:
// example.h
struct Parent {
virtual void foo(double) {}
};
struct Child : Parent {
void foo(double d) { bar(d); }
template<typename T> void bar(T);
virtual void baz();
};
// example.cpp
#include "example.h"
template <typename T>
void Child::bar(T) {}
void Child::baz() {}
Compiling this with [g++|clang++] -c example.cpp
, both GCC and clang implicitly instantiate the function template Child::bar<double>
. However, the following seemingly minor changes prevent this:
- Making
foo
not virtual - Making
Child
not inherit fromParent
- Removing
baz
- Making
baz
not virtual - Defining
baz
with the declaration in the header
Is there any reasonably concise explanation of when implicit instantiation takes place, or do I need to wade through a copy of the standard? I've searched SO for other questions relating to implicit instantiation, but didn't find much. The closest I found was this question, but it's about virtual functions in class templates (not member function templates).
To be clear: I understand that this issue can be avoided by either including the definition in the header or explicitly instantiating the templates that I need. This merely arose as a point of curiosity when digging into why one class (whose explicit instantiations I had inadvertently omitted) nonetheless happily compiled and linked.