The following C++ code does not compile e.g. with g++-4.7 or clang++-3.2:
struct Bar {};
template<typename T>
void foo(T t, Bar bar) {
t.compiler_does_not_care();
bar.nonexistent_method();
}
int main() {}
Why do compilers check the code of the template function foo for semantic correctness (where they can) even though it is never instantiated? Is this standard compliant?
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).
In template definitions, typename provides a hint to the compiler that an unknown identifier is a type. In template parameter lists, it's used to specify a type parameter.
There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.
Which one is suitable syntax for function template? Explanation: Both class and typename keywords can be used alternatively for specifying a generic type in a template.
Bar
is a non dependent name (i.e. its type does not depend on T
), so the compiler is required to verify the correctness of the code during the first phase of name-lookup (see the note below).
Since Bar
has no nonexistent_method()
method, the compiler is required to issue a diagnosis.
If you change your template to:
template<typename T>
void foo(T t, T bar) {
t.compiler_does_not_care();
bar.nonexistent_method();
}
No non-dependent names are involved, so no error is emitted since the template is never instantiated (phase 2 of the lookup)
Notes:
1) Template definition time: when the template is initially parsed, long before it is instantiated, the compiler parses the template and looks up any "non-dependent" names. A name is "non-dependent" if the results of name lookup do not depend on any template parameters, and therefore will be the same from one template instantiation to another.
2) Template instantiation time: when the template is instantiated, the compiler looks up any "dependent" names, now that it has the full set of template arguments to perform lookup. The results of this lookup can (and often do!) vary from one template instantiation to another.
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