GotW #87

Home Blog Talks Books & Articles Training & Consulting

On the
RSS feed November 4: Other Concurrency Sessions at PDC
November 3
: PDC'09: Tutorial & Panel
October 26: Hoare on Testing
October 23
: Deprecating export Considered for ISO C++0x

Two-Phase or Not Two-Phase:
The Story of Dependent Names in Templates
Difficulty: 9 / 10

In the land of C++, there are two towns: The village of traditional nontemplate C++ code, and the hamlet of templates. The two are tantalizingly similar, and so many things are the same in both places that visitors to the templates hamlet might be forgiven for thinking they're right at home, that the template programming environment is the same as it was in their familiar nontemplate surroundings. That is a natural mistake… but some of the local laws are different, often in subtle ways, and some classic assumptions must be unlearned before one can learn to write template code correctly and portably. This articles explores these small but important differences, and how they will soon increasingly affect your code.


JG Questions

1. In the following code statement, what could f be? List as many possibilities as you can.

f( a, b );

2. Describe at a high level how a C++ compiler performs name lookup on a name like f from Question 1.

Guru Questions

3. In a C++ template:

a) What are dependent names and nondependent names?

b) In the following code, for each line, answer whether or not the line contains a dependent name:

template<typename T>
class X : public Y<T> {  // 1 ?
  E f( int ) {           // 2 ?
    g();                 // 3 ?
    this->h();           // 4 ?

    T t1, t2;
    cout << t1;          // 5 ?
    swap( t1, t2 );      // 6 ?
    std::swap( t1, t2 ); // 7 ?

4. In a C++ template, what do "point of definition" and "point of instantiation" mean?


This marks the final issue of GotW. A written-out solution was not posted, but here are brief notes:

1. f could be a function or a function object.

2. See these other articles on this site for details on name lookup.

3. Dependent names are names that depend in some way (e.g., qualification) on a template parameter. In this example, lines 1, 4, 5, and 6 contain dependent names and expressions.

4. A template's point of definition is the place where the template code is define. Informally, the point of instantiation is the first point where you use the template or a member of the template; the instantiation could be implicit or explicit.

I hope you've enjoyed GotW over the years! Best wishes,


Copyright © 2009 Herb Sutter