Search code examples
c++typedef

How can I typedef a namespace qualified type?


I want to do something along the lines of #define std::unordered_map my_namespace::my_map. There are various complicated reasons for why I want to do this (legacy code, future upstream merging, performance, etc.). Unfortunately, #define doesn't work with :: and typedef seems to have issues as well. How might I do this?

Typedef's issue:

  • typedef std::unordered_map my_namespace::my_map; gives the error "Typedef declarator cannot be qualified".
  • namespace std { typedef unordered_map my_namespace::my_map }; gives the error "Cannot define or redeclare 'my_map' here because namespace 'std' does not enclose namespace 'my_namespace'"

Solution

  • How can I typedef a namespace qualified type?

    You define a typedef for a (type that is in a namespace) like this:

    typedef some_ns::type alias;
    

    You define a (typedef that is in a namespace) for a type like this:

    namespace other_ns {
        typedef some_ns::type alias;
    }
    

    Or, you can use the corresponding using syntax, which I recommend:

    namespace other_ns {
        using alias = some_ns::type;
    }
    

    I want std::unordered_map to be an alias for my_namespace::my_map

    You may not add typedefs into the std namespace. That is reserved to the language implementation. This is simply not possible in C++.


    namespace std { typedef unordered_map my_namespace::my_map };
    

    You have the alias and the target type in wrong order. This makes std::my_namespace::my_map an alias of std::unordered_map. Or it would, if you were allowed to put the qualified names in the typedef, which you aren't. Considering you intuitively use the order of [alias, type], the using syntax should fit you just right.

    Regardless, see the previous section about std being a reserved namespace.