C++ inherit template class

余生颓废 提交于 2019-12-25 00:34:48

问题


I've got a peculiar request, hopefully it's not too far fetched and can be done.

I've got a template class

    template<class T> class Packable
    {
    public:
        // Packs a <class T> into a Packet (Packet << T)
        virtual sf::Packet& operator <<(sf::Packet& p) const = 0;
        friend sf::Packet& operator <<(sf::Packet& p, const T &t);
        friend sf::Packet& operator <<(sf::Packet& p, const T *t);


        // Packs a Packet into a <class T> (T << Packet)
        virtual T operator <<(sf::Packet& p) const = 0;
        friend T& operator <<(T &t, sf::Packet& p);
        friend T* operator <<(T *t, sf::Packet& p);

        // Unpacks a Packet into a <class T> (Packet >> T)
        virtual sf::Packet& operator >>(sf::Packet& p) const = 0;
        friend sf::Packet& operator >>(sf::Packet& p, T &);
        friend sf::Packet& operator >>(sf::Packet& p, T* t);
    };

and I want to be able to use it something like

class Player : public Packable
{
    //...
}

Such that Player now has all of those operators overloaded for it.

As of now, I get Expected class name as a compile error. Is there a way to accomplish this without needing to specify the class? That is to say; how can Packable pick up Player as <class T> when I inherit it?


回答1:


I guess you want something like the following:

class Player: public Packable<Player>
    //...



回答2:


Yes, you need to do

template <typename T>
class Player: public Packable<T>
{
...
}


来源:https://stackoverflow.com/questions/23725631/c-inherit-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!