It is important to realize that a class template is not a class, but only a blueprint for one.
A<char,2>
matches the specialized blueprint, so it has f,g,h
member functions. Contents of the primary template are completely ignored.
Because A
is a template class, its methods are instantiated only when actually called and only for those concrete template arguments because instantiation of A
is a class, thus it has only one set of methods.
- Since you did not define any
A<char,2>::f
, the linker reports undefined reference
error.
- There is a definition of
A<char,2>::g
available by instantiating template<class T> void A<T,2>::g()
function - that is an ordinary method, not a function template.
- For the same reason,
A<char,2>::h
also compiles - there is a definition for this function, nothing more is required.
In a nutshell, the compiler will only look for the definitions it needs, if it finds a matching template, it will generate the definitions. Otherwise it will mark the symbol as missing and it is your responsibility that the linker will have it available.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…