Dmitrii Bundin Dmitrii Bundin - 7 days ago 6
C++ Question

Can member function be treated as a template?

The section

N4296::14.5.1/3 [temp.class]
:


When a member function, a member class, a member enumeration, a static
data member or a member template of a class template is defined
outside of the class template definition, the member definition is
defined as a template definition in which the template-parameters are
those of the class template.


My question is can member functions be treated as templates? I think this is important, because the function template won't be implicitly instantiated if it's not called. Example:

template<class T>
struct A
{
void foo(){ }
void bar(){ }
};

int main()
{
A<int> *a = new A<int>; //Instantiation of the struct A<int>

a -> foo(); //Now we know the function foo was instantiated implicitly.
//But what about the bar function?
}


DEMO

Answer

The member function declaration is instantiated at the time the class template specialization is implicitly instantiated.

A non-virtual member function definition is not implicitly instantiated until it is actually used.

This is why we can have vector<unique_ptr<int>> even though its copy constructor will not compile.


Standardese:

[temp.inst]/p1,2,11:

1 Unless a class template specialization has been explicitly instantiated (14.7.2) or explicitly specialized (14.7.3), the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program. The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions, default arguments, or exception-specifications of the class member functions, member classes, scoped member enumerations, static data members and member templates; and it causes the implicit instantiation of the definitions of unscoped member enumerations and member anonymous unions. [...]

2 Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; [...]

11 An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation. It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated.

Comments