Uses for anonymous namespaces in header files

Someone asserted on SO today that you should never use anonymous namespaces in header files. Normally this is correct, but I seem to remember once someone told me that one of the standard libraries uses anonymous namespaces in header files to perform some sort of initialization.

Am I remembering correctly? Can someone fill in the details?


The only situation in which a nameless namespace in header can be useful is when you want to distribute code as header files only. For example, a large standalone subset of Boost is purely headers.

The token ignore for tuples, mentioned in another answer is one example, the _1, _2 etc. bind placeholders are others.


I don't see any point in putting an anonymous namespace into a header file. I've grepped the standard and the libstdc++ headers, found no anonymous namespaces apart of one in the tuple header (C++1x stuff):

  // A class (and instance) which can be used in 'tie' when an element
  // of a tuple is not required
  struct _Swallow_assign
  {
    template<class _Tp>
      _Swallow_assign&
      operator=(const _Tp&)
      { return *this; }
  };

  // TODO: Put this in some kind of shared file.
  namespace
  {
    _Swallow_assign ignore;
  }; // anonymous namespace

This is so you can do

std::tie(a, std::ignore, b) = some_tuple;

elements of the some_tuple are assigned the variables at the left side (see here), a similar technique is used for this iterator. The second element is ignored.

But as they say, it should be put into a .cpp file and the one instance should be shared by all users. They would put a declaration of it into the header like this then:

extern _Swallow_assign ignore;

I've seen it used to provide a default value for a variable in different translation units. But it could cause unexpected behaviour in the case of name clashes.

Example

a.hpp

namespace
{
    const char name[] = "default";
}
// This macro will hide the anonymous variable "name"
#define SET_NAME(newname) \
static const char name[] = newname;

b.cpp

#include "a.hpp"
SET_NAME("file b") // name is "file b" in this translation unit

c.cpp

#include "a.hpp"
SET_NAME("file c") // name is "file c" in this translation unit

d.cpp

#include "a.hpp"
// name is "default" in this translation unit

e.cpp

#include "a.hpp"
static const char name[] = "unintended";
// accidently hiding anonymous name

I really can see no positive benefit from using anonymous namespaces in headers. The confusion that can result from having the same symbol declaration mean, in essence, a different thing in the compilation units that include that header would be a guaranteed way to go prematurely and painfully bald.