简体   繁体   中英

Can I inherit a template class and set the type to a templated subclass of the class I'm currently trying to inherit from?

Terrible title, I know. I'll illustrate:

template <typename ValType> struct MemMapFileHashTable : MemMapFileStructured<MemMapFileHashTable<ValType>::kvp> {
    struct kvp {
        uint32_t key;
        ValType val;
    };

    MemMapFileHashTable(const char* fileName, bool write = false, int64_t chunkB = 65536) : MemMapFileStructured(fileName, write, chunkB) { }
};

So the idea is that I create a hash table with a certain ValType which in turn has kvp's with a certain ValType.

To make use of the class I'm inheriting, I need to set the kvp as the type specifier, however since the kvp is declared inside the hash table class it won't let me. Is there a way to persuade it otherwise?

I could just create an instance of MemMapFileStructured inside the hash table I guess but this would be the 5th successive inheritance in the line of classes I've built and I don't want to break my roll.

You can achieve equivalent results using an extra declaration, and a typedef . Example:

template<typename ValType> struct kvp_t {
    uint32_t key;
    ValType val;
};

template <typename ValType> struct MemMapFileHashTable : MemMapFileStructured<kvp_t<ValType>> {

    typedef kvp_t<ValType> kvp;

    MemMapFileHashTable(const char* fileName, bool write = false, int64_t chunkB = 65536) : MemMapFileStructured(fileName, write, chunkB) { }
};

If you feel like you want to continue to use the type kvp in your main template, be my guest. Nobody will be able to tell the difference. MemMapFileHashTable<ValType>::kvp will still be what you expect to be. It can be our little secret, that it's really something else.

In fact, if you poke around your C++ compiler's library, you will probably discover that things like, oh, say std::vector<TYPENAME>::iterator is really some other template. It happens all the time.

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