views:

91

answers:

1

Hello everyone,

I'm a pretty novice (C++) programmer and have just discovered the CRTP for keeping count of objects belonging to a particular class.

I implemented it like this:

template <typename T>
struct Counter
{
    Counter();
    virtual ~Counter();

    static int count;
};

template <typename T> Counter<T>::Counter()
{
    ++count;
}

template <typename T> Counter<T>::~Counter()
{
    --count;
}

template <typename T> int Counter<T>::count(0);

which seems to work. However, it doesn't seem to like inheriting from it in a separate header file, where I declared this:

class Infector : public Counter<Infector>
{
    public:
        Infector();
        virtual ~Infector();

        virtual void infect(Infectee target);
        virtual void replicate() = 0;
        virtual void transmit() = 0;

    protected:
    private:
};

Everything compiles just fine without the inheritance, so I'm fairly sure it can't see the declaration and definition of the template. Anybody have any suggestions as to where I might be going wrong and what I can do about it? Should I be using extern before my Infector definition to let the compiler know about the Counter template or something like that?

Cheers,

Kyle

+2  A: 

I noticed you specifically mentioned declarations and definitions.
Do you have them in separate files?

If so, templates are header only creatures. You'll need to put your definitions in the header file.

Chris Bednarski
Ahh, awesome. Thanks a lot. I'll move the template to a header file, I had it as a linked object file, which I guess isn't sufficient for the rest of the code to be aware of it. Cheers.
Kyle_S-C