开发者

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> Count开发者_运维问答er<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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜