Migrating to Namespaces
by Herb P. Sutter

Example 1: 

(a)
#include <iostream.h>
int main()
{
  cout << "hello, world" << endl;
}

(b)
#include <iostream>
int main()
{
  std::cout << "hello, world" << std::endl;
}

(c)
#include <iostream>
using std::cout;
using std::endl;
int main()
{
  cout << "hello, world" << endl;
}

(d)
#include <iostream>
using namespace std;
int main()
{
  cout << "hello, world" << endl;
}

Example 2: 
(a)
//--- file x.h ---
#include "y.h"  // defines Y
#include <deque>
#include <iosfwd>

ostream& operator<<( ostream&, const Y& );
int f( const deque<int>& );

//--- file x.cpp ---
#include "x.h"
#include "z.h"  // defines Z
#include <ostream>

ostream& operator<<( ostream& o, const Y& y )
{
  // ... uses Z in the implementation ...
  return o;
}
int f( const deque<int>& d )
{
  // ...
}


(b)
//--- file x.h ---
#include "y.h"  // defines Y
#include <deque>
#include <iosfwd>

std::ostream& operator<<( std::ostream&, const Y& );
int f( const std::deque<int>& );

//--- file x.cpp ---
#include "x.h"
#include "z.h"  // defines Z
#include <ostream>
using std::deque;   // using declarations appear
using std::ostream; //  AFTER all #includes

ostream& operator<<( ostream& o, const Y& y )
{
  // ... uses Z in the implementation ...
  return o;
}
    int f( const deque<int>& d )
    {
      // ...
    }

(c)
//--- file x.h ---
#include "y.h"  // defines MyProject::Y and adds using declarations/directives
                //  in namespace MyProject
#include <deque>
#include <iosfwd>

namespace MyProject
{
  using std::deque;
  using std::ostream;
  // or, "using namespace std;"
  ostream& operator<<( ostream&, const Y& );
  int f( const deque<int>& );
}
//--- file x.cpp ---
#include "x.h"
#include "z.h"  // defines MyProject::Z and adds using declarations/directives
                //  in namespace MyProject
  // error: potential future name ambiguities in z.h's declarations, 
  //   depending on what using declarations exist in headers that happen to 
  //   be #included before z.h in any given module (in this case, x.h or y.h 
  //   may cause potential changes in meaning)
#include <ostream>

namespace MyProject
{
  ostream& operator<<( ostream& o, const Y& y )
  {
    // ... uses Z in the implementation ...
    return o;
  }
  int f( const deque<int>& d )
  {
    // ...
  }
}


(d)
//--- file x.h ---
#include "y.h"  // defines Y
#include <deque>
#include <iosfwd>

std::ostream& operator<<( std::ostream&, const Y& );
int f( const std::deque<int>& );

//--- file x.cpp ---
#include "x.h"
#include "z.h"  // defines Z
#include <ostream>
#include "myproject_last.h" // AFTER all other #includes
ostream& operator<<( ostream& o, const Y& y )
{
  // ... uses Z in the implementation ...
  return o;
}
int f( const deque<int>& d )
{
  // ...
a}
//--- common file myproject_last.h ---
using namespace std;



3

