Suppose you have the following (ill-formed) program:
struct A
{
A(int, int)
{
}
};
template <typename T>
class B
{
B()
{
if (sizeof (T) == 1)
{
throw A(0); // wrong, A() needs two arguments
}
}
};
int main()
{
return 0;
}
GCC compiles this program without any errors, clang++ refuses it with an error.
The bodies of template classes and inline (or static) template functions are always instantiated implicitly when their definitions are needed. Member functions of template classes are not instantiated until they are used. Other template items can be instantiated by using explicit instantiation.
Templates are instantiated in the process of converting each translated translation unit into an instantiation unit. A translation unit is essentially a source file. A translated translation unit (try to say that three times fast) is the output from compilation without templates instantiated.
In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
Class Template DeclarationA class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration.
The template is instantiated when used. However, it should be compiled when it's defined. Your code A(0)
uses the name A
, which doesn't depend on the template parameter T
, so it should be resolved when the template is defined. This is called two-phase lookup. The way clang finds the error is simply by trying to resolve the call A(0)
as soon as it sees it.
My version of GCC also compiles this code silently, even with -pedantic-errors
. Both C++03 and C++11 say that no diagnostic is required, even though the program is ill-formed, so GCC conforms. This is 14.6/7 in C++03 and 14.6/8 in C++11:
If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required.
Yes. When no valid specialization exist but the template isn't instantiated -- like here -- the program is ill-formed, but no diagnostic is required (14.6/8). So both clang and g++ are right.
clang does more checks than g++ on the template declaration.
See above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With