Topic: When a default argument cause template instantiation
Author: pescio@my-deja.com
Date: 2000/09/17 Raw View
Consider a class template like the following, that when instantiated
will probably generate some warnings (I know that warnings are outside
the standard, but anyway):
template< int N > struct Deprecated
{
Deprecated( int ) {}
~Deprecated()
{
int* deprecated;
*deprecated = 0 ; // vc++, bc++ catch this
deprecated[3] ; // gcc 2.95, -W[all] catch this
}
} ;
Now consider a function, taking a reference to a specialization of that
class as a parameter, with a default value that will cause a temporary
to be created:
// prototype
void f( int& a , const Deprecated< 0 >& d = 0 ) ;
// definition
void f( int& a , const Deprecated< 0 >& )
{
++a ;
}
Obviously, if you include all the above in a compilation unit, followed
by a main() like this:
int main()
{
int x = 3 ;
f( x ) ; // line XXX
return 0 ;
}
you get a warning, which (with some luck) you can trace back to line
XXX.
My question is: what should happen if you comment out line XXX? A few
compilers that I have tried (Visual C++ 6, C++ Builder 5, gcc 2.95),
seeing no *calls* to f, will not instantiate Deprecated, and no warning
will be generated. Still, with other compilers (like Comeau 4.2.43) you
always get a warning.
The real issue is: does the declaration/definition of f cause an
implicit instantiation of Deprecated< 0 >? From my understanding of the
standard it should not: 14.7.1p9 says "the use of a template
specialization in a default argument shall not cause the template to be
implicitly instantiated except that a class template may be
instantiated where its complete type is needed to determine the
correctness of the default argument". The "except ..." part
does not seem to apply (?), so I would expect Deprecated to be
instantiated, and a warning to be generated, *only* if f() is actually
called.
Opinions, suggestions, reports from other compilers would be much
appreciated.
Have fun,
Carlo Pescio
Sent via Deja.com http://www.deja.com/
Before you buy.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]