C++ type aliases in anonymous namespace

I understand the general use of anonymous namespaces to contain code that should be only visible to the current source (i.e. non-header) file. However, I'm not able to find any information on what happens in the case below:

// In foo.cpp

#include <vector>

// Choice #1
template <typename T>
using Vec1 = std::vector<T>;

// Choice #2
namespace {

template <typename T>
using Vec2 = std::vector<T>;

}

Do Vec1 and Vec2 differ in any way? Since I can't think of a way to have an "extern" type alias in a header file to reference Vec1, I'm not sure if the anonymous namespace here achieves anything.


Anonymous namespaces primarily affect linkage. A type alias alone has no linkage, so in your case the two are identical.

That said, it is possible some included header also defines a template type alias with the same name but it's aliasing a different type. Then there is a difference; if you keep all of your implementation-detail functions also in the same anonymous namespace as your alias, there will be no error whereas for the non-namespaced alias you wrote, the program would be ill-formed.


We use anonymous namespaces in general so that we don't accidentally provide an implementation of a function declared in another header. They can also be used to ensure we are not defining storage for an extern variable declared elsewhere.

With a type alias, there is no risk of leaky implementations.