Kyle_S-C
Kyle_S-C

Reputation: 1177

Using the "curiously recurring template pattern" in a multi-file program

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

Upvotes: 0

Views: 490

Answers (1)

Chris Bednarski
Chris Bednarski

Reputation: 3414

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.

Upvotes: 2

Related Questions