使用“奇怪地重复出现的模板模式”在多文件程序中

发布于 2024-09-08 17:15:30 字数 897 浏览 3 评论 0原文

我是一个相当新手(C++)程序员,刚刚发现了 CRTP 来记录属于特定类的对象的数量。

我是这样实现的:

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);

这似乎有效。但是,它似乎不喜欢在单独的头文件中继承它,我在其中声明了这一点:

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

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

    protected:
    private:
};

没有继承,一切都编译得很好,所以我相当确定它看不到模板的声明和定义。有人对我可能出错的地方以及我能做些什么有任何建议吗?我应该在 Infector 定义之前使用 extern 来让编译器了解 Counter 模板或类似的东西吗?

干杯,

凯尔

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浊酒尽余欢 2024-09-15 17:15:30

我注意到您特别提到了声明和定义。
您将它们放在单独的文件中吗?

如果是这样,模板只是标题生物。您需要将定义放入头文件中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文