nitronoid
nitronoid

Reputation: 1609

Scope a using declaration, inside a header

Unfortunately I'm bound to using a thirdparty macro which assumes that I am within the namespace thirdparty. However this macro declares some types which I need to be outside of the thirdparty namespace, so I can't use this snippet:

namespace thirdparty
{
  TP_MACRO(my_type_name, inner);
}

If I did, all of my declared types would be in the thirdparty:: namespace which won't work.

The issue is that the TP_MACRO is using types from inside of the thirdparty namespace without qualifying them. To get arround the this I am currently bringing these types into the current scope with using declarations:

using thirdparty::type1;
using thirdparty::type2;

TP_MACRO(my_type_name, inner);

The downside of this approach is that I'm polluting the global namespace with these types, which is generally bad practice (this code is in a header file).

I can wrap the above snippet in a new namespace (which I am doing), but I would like to know if there is a way to scope these using declarations so that after the macro has declared my types, I can remove them from the surrounding namespace?

The TP_MACRO is similar to (but is more complex in reality):

#define TP_MACRO (name, inner)         \
    typedef type1<inner> type1_##name; \
    typedef type2<inner> type2_##name;

It is also subject to change, hence why I would avoid copying it's contents.

Upvotes: 0

Views: 169

Answers (2)

Nikos C.
Nikos C.

Reputation: 51850

Try declaring the types in an embedded namespace inside thirdparty so that the macro is happy, then alias that namespace so that it's accessible globally:

namespace thirdparty::myns {
    TP_MACRO(my_type_name, inner);
}

namespace myns = thirdparty::myns;

If you are not using C++17, then use:

namespace thirdparty {
    namespace myns {
        TP_MACRO(my_type_name, inner);
    }
}

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385204

I can wrap the above snippet in a new namespace (which I am doing)

That's what you should be doing.

I would like to know if there is a way to scope these using declarations so that after the macro has declared my types, I can remove them from the surrounding namespace?

No.


Also I suggest making a recommendation upstream that they improve these macros.

Upvotes: 2

Related Questions