使用“奇怪地重复出现的模板模式”在多文件程序中
我是一个相当新手(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我注意到您特别提到了声明和定义。
您将它们放在单独的文件中吗?
如果是这样,模板只是标题生物。您需要将定义放入头文件中。
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.