[英]Template class on a abstract class
So I have a class template Foo
: 所以我有一个类模板
Foo
:
template <typename T>
class Foo
{
public:
Foo();
~Foo();
//...
};
I have two derived classes from the Foo class: 我有两个从Foo类派生的类:
class FooDerived1 : public Foo<int>
{
public:
FooDerived1 ();
~FooDerived1 ();
};
class FooDerived2 : public Foo<double>
{
public:
FooDerived2 ();
~FooDerived2 ();
};
But now I saw that the class template was being used on a abstract class IBar
like this: 但是现在我看到类模板正在这样的抽象类
IBar
上使用:
class Foo;
class IBar
{
public:
virtual void placeFoo(Foo& foo) = 0; //error
virtual void removeFoo(Foo& foo) = 0;
};
I know I cannot use templates classes in abstract virtual classes. 我知道我不能在抽象虚拟类中使用模板类。
But..in a case like this, what should I do? 但是..在这种情况下,我该怎么办?
I really need the IBar abstract class like this... 我真的需要像这样的IBar抽象类...
Forget the usage of template classes? 忘记模板类的用法了吗?
Option 1: Make IBar
itself a template class. 选项1:将
IBar
本身作为模板类。
template <class T>
class Foo;
template <class T>
class IBar
{
public:
virtual void placeFoo(Foo<T>& foo) = 0;
virtual void removeFoo(Foo<T>& foo) = 0;
};
Option 2: Make all Foo<T>
derive from a common, non-generic FooBase
. 选项2:使所有
Foo<T>
都从公共的非泛型FooBase
。
class FooBase
{
// ...
};
template <typename T>
class Foo : public FooBase
{
public:
Foo();
~Foo();
//...
};
// ...
class FooBase;
class IBar
{
public:
virtual void placeFoo(FooBase& foo) = 0;
virtual void removeFoo(FooBase& foo) = 0;
};
The viability of both solutions depends on how much you actually depend on the T
type. 两种解决方案的可行性取决于您实际上对
T
类型的依赖程度。 But that's what you should expect when you mix virtual functions with templates. 但这是将虚拟功能与模板混合使用时的期望。 With option 1, you do not have a common interface type anymore;
使用选项1,您将不再具有通用接口类型。 with option 2,
FooBase
cannot provide any member function with a T
-dependent argument. 使用选项2,
FooBase
无法为任何成员函数提供T
依赖的参数。
By the way, don't forget about virtual destructors in your real code. 顺便说一句,不要忘记您的真实代码中的虚拟析构函数。
If you need common behaviour, create base class for all instances of Foo<>
: 如果需要共同的行为,请为
Foo<>
所有实例创建基类:
class FooBase
{
//common interface and data
};
template <class T>
class Foo : public FooBase
{
};
And then: 接着:
class FooBase;
class IBar
{
public:
virtual void placeFoo(FooBase& foo) = 0; //ok
virtual void removeFoo(FooBase& foo) = 0;
};
The thing is, that you try to mix templates (compile time) and dynamic polymorphism (runtime), which can be problematic (is it what you meant by "I know I cannot use templates classes in abstract virtual classes" ?). 事实是,您尝试将模板(编译时)和动态多态性(运行时)混合在一起,这可能会引起问题(这是您所说的“我知道我无法在抽象虚拟类中使用模板类”的意思吗?)。
Why not stick to using templates? 为什么不坚持使用模板呢?
class IBar
{
public:
template <class T>
void placeFoo(Foo<T>& foo);
template <class T>
void removeFoo(Foo<T>& foo);
};
or: 要么:
template <class T>
class IBar
{
public:
void placeFoo(Foo<T>& foo);
void removeFoo(Foo<T>& foo);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.