mercredi 23 septembre 2015

C++ using declaration vs type aliases in headers

In a C++11 project I would like to introduce a few identifiers from the standard library namespace (std) into the project's namespace (proj) to enhace readability. For example I would prefer to be able to use string everywhere instead of std::string.

Note that this project is an application, not a library whose code will be subsequently included by other projects.

This could be achieved by adding code to a common header included everywhere in the project. Two methods of actually introducing the identifier are shown below:

#ifndef PROJ_H
#define PROJ_H

#include "stuff.h"
#include <string>

namespace proj
{
  // method 1 - using declaration
  using std::string;

  // method 2 - type alias
  using string = std::string;
}

#endif

I have a feeling that method 2 is superior to method 1. The reason being that if stuff.h introduces a string identifier to the anonymous namespace then use of string from inside the proj namespace will be ambiguous.

My questions:

  1. Is method 2 really superior as I suggest or are they strictly equivalent?
  2. If method 2 is better, how can I achieve the same level of safety for a non-type identifier (such as a function like std::make_unique).

Aucun commentaire:

Enregistrer un commentaire