1

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?

Volte
  • 1,905
  • 18
  • 25
  • 1
    Read about the [Curiously recurring template pattern](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern). – Some programmer dude May 18 '14 at 18:55
  • It is very usual to have to specify `Player` twice. The only way to avoid doing so (while using the same design) is to use the preprocessor, which would be hideous. – Mankarse May 18 '14 at 18:58

2 Answers2

2

I guess you want something like the following:

class Player: public Packable<Player>
    //...
Appleshell
  • 7,088
  • 6
  • 47
  • 96
  • This works! Thanks @Appleshell. Too bad it can't be a bit cleaner, but hey, this is C++ :) – Volte May 18 '14 at 18:56
  • I haven't forgotten don't worry! If I have a follow up question or additional information (namespaces) should I make a new question or amend this one? – Volte May 19 '14 at 02:28
  • @Volte Opinions differ ([\[1\]](http://meta.stackexchange.com/questions/156900/whats-the-policy-on-follow-up-questions)[\[2\]](http://meta.stackexchange.com/questions/10243/asking-a-follow-up-question)[\[3\]](http://meta.stackexchange.com/questions/19457/where-should-i-post-follow-up-questions)), but I'd say it's good to create a new question for follow up questions. – Appleshell May 19 '14 at 02:34
  • http://stackoverflow.com/questions/23729016/namespaced-class-template-inheritance-in-c :) – Volte May 19 '14 at 02:47
0

Yes, you need to do

template <typename T>
class Player: public Packable<T>
{
...
}
vsoftco
  • 55,410
  • 12
  • 139
  • 252