The template class method does not cause an error - is this part of the standard?

When I compile the following with g++ --std=c++98 -Wall -Werror -Wpedantic Test.cc , there is no error.

 template <class T> struct TemplateClass { T *ptr; TemplateClass(T *p): ptr(p) {} int foo() { return ptr->bar(); } }; struct ExampleClass { }; int main() { TemplateClass<ExampleClass> x(new ExampleClass()); } 

I expected the compiler to complain that ExampleClass does not implement the bar method.

But it looks like he is only complaining if I really use the foo method.

Can I rely on this behavior on any compilers compatible with C ++ 98 and C ++ 11?

My understanding of patterns previously was that whenever a pattern is instantiated, all of it is copied with T replaced by the pattern argument. Isn't that how templates work?

+6
source share
1 answer

This is the correct behavior according to the standard. The definition of foo not created until it is used in a context that requires its existence. Underline the shaft below:

C ++ 03, [temp.inst] / 1:

Implicit instantiation of template template specialization causes an implicit instance of declarations, but not default definitions or arguments, class member functions, member classes, static data elements and member templates; and this causes the implicit creation of definitions of membership anonymous unions. If a class template member or member template is not explicitly created or is not explicitly specialized, the specialization of the member is implicitly an instance when the specialization is referenced in a context that requires the definition of the member; ...

C ++ 11, [temp.inst] / 1 and [temp.inst] / 2:

If the specification of the class template has not been explicitly created (14.7.2) or explicitly specialized (14.7.3), the specialization of the class template is implicitly created when the specialization is referenced in a context that requires a fully defined type of object or when the completeness of the class type affects the semantics of the program. Implicit instance creation of a template template specialization causes implicit and not <definition> or default arguments, class member functions, member classes, cloud element names, static data elements and member templates; ... if the class template member or element template does not has been explicitly defined or explicitly specialized, a member specialization is implicitly created when a specialization is referenced in a context that requires a member definition; ...

+11
source

All Articles