简体   繁体   中英

Inherit dependent typedef without using struct

I have some code like this:

#include <string>
#include <map>

typedef std::less<std::string> Comparator; // simplified

typedef std::allocator<std::pair<const std::string, int>> Allocator; // simplified

template<class T>
struct Base
{
    typedef std::map<std::string, T, Comparator, Allocator> type; // VERY long declaration in the actual code
};

template<class T>
struct Container : public Base<T>::type
{
    Container(Allocator a) : Base<T>::type(Comparator(), a) {}
};

int main()
{
    Allocator a;
    Container<int> c(a);
}

Although the declarations are a bit more fancy in my actual code.

The Base struct is used so that I do not have to write the long map declaration multiple times.

I was wondering if there is a better way to inherit from the map without any Base struct?

No macros please. I hope in some way to hide the typedef in the Container class itself or something like that.

Thanks,

You can rely on templates having an injected class name. Inside the specialization of map<...> , the current specialization can be referred to simply by map . And that injected class name is also available to derived classes (and class templates). But since it's dependent, it requires a qualified name. It looks simpler than it sounds, here's how you roll the alias into Conatiner :

template<class T>
struct Container : public std::map<std::string, T, Comparator, Allocator>
{
    using Base = typename Container::map;
    Container(Allocator a) : Base(Comparator(), a) {}
};

Container::map is the injected class name. And the alias grabs it for convenient use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM