0

Possible Duplicate:
Two phase lookup - explanation needed

When I'm using a template class the compiler doesn't show me errors/warning of missing #includes.

For example, If I have a class called "A" and it looks much or less like this :

template<class T>
class A {
    void print() const {cout << "Hey I didn't use include for 
                                 iostream and It works just fine!!!";}
};

If I remove the template < class T > I get errors of the absence of <iostream >include.

Why the compiler doesn't show these errors when I'm using template class ?

Just to point out, when I say It works I mean It doesn't show me any compilation errors when I'm writing the class but only when I use it as opposed to a non-template class whereas the error shows immediately.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1942476
  • 435
  • 1
  • 5
  • 8
  • 4
    Two related questions: *what*: [Two phase lookup](http://stackoverflow.com/questions/7767626/two-phase-lookup-explanation-needed) and *why*: [Two phase name lookup for C++ templates - Why?](http://stackoverflow.com/questions/12561544/two-phase-name-lookup-for-c-templates-why?lq=1) – jrok Jan 16 '13 at 09:50

2 Answers2

2

When you write template code, a huge bulk of the syntax checking happens only if and when you make an instance of this class, if it is never used, it is never checked.

To verify this, add this line at the end, A<int>;

More information at Two phase lookup - explanation needed as jrok points out.

Edit:

The linked posts bring up an interesting point, this does error out on gcc and clang even without an instantiation. I guess like myself, you are on MSVC++

Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
1

When the compiler first parses your template, it is only required to perform the most basic syntax checks and type checking for non-dependent types (types which are not defined in terms of the template arguments). For each member function of a fully specialized templated type, all type-checking on dependent types (those that depend on template arguments) only needs to be done the first time it comes across an expression using that function (for example by calling it). This also means that any member function you don't use (for a particular specialization) of a templated type might not be fully compiled at all.

This is called two-phase name lookup and (as mentioned in the other answers) you can find more information about it here: Two-phase lookup

Community
  • 1
  • 1
Agentlien
  • 4,996
  • 1
  • 16
  • 27