Anonymous namespace in template implementation file

432 Views Asked by At

In a .cpp file, an anonymous namespace basically has file-wide linkage (after #includes) because the .cpp file will never be included by another file. But, the same pattern in a header file propagates that anonymous namespace to wherever it is included in. Is there a way to create a similar effect in a header file? I ask because template implementations must be in headers.

A simple example in a regular .h file would be this:

// object.h

namespace {
    using verbose::namespace::type;
}

...

struct object {  
    type value;
}

or similarly in some template implementation file. The type type would be in-scope of wherever this file is included.

Is there a way around this?

EDIT: I think I found a verbose but workable answer.

// object.h

struct Namespace {
     using verbose::namespace::type;

     Namespace() = delete;

     struct object {
         type value;
     };
};

using Namespace::object;
1

There are 1 best solutions below

2
Nicholas Pipitone On

This should do the trick:

// object.h
{
    namespace {
        using verbose::namespace::type;
    }

    ...

    struct object {  
        type value;
    }
}

Namespaces should only be valid within the code block they're defined in.