问题描述
我有如下代码.我有一个抽象模板类 Foo 和两个从模板实例派生的子类(Foo1 和 Foo2).我希望在我的程序中使用可以指向 Foo1 或 Foo2 类型对象的指针,因此我创建了一个接口 IFoo.
I have the code as below. I have a abstract template class Foo and two subclasses (Foo1 and Foo2) which derive from instantiations of the template. I wish to use pointers in my program that can point to either objects of type Foo1 or Foo2, hence I created an interface IFoo.
我的问题是我不确定如何在接口中包含 functionB,因为它依赖于模板实例化.甚至可以通过接口访问 functionB,还是我在尝试不可能的事情?
My problem is I'm not sure how to include functionB in the interface, since it is dependant on the template instantiation. Is it even possible to make functionB accessible via the interface, or am I attempting the impossible?
非常感谢您的帮助.
class IFoo {
public:
virtual functionA()=0;
};
template<class T>
class Foo : public IFoo{
public:
functionA(){ do something; };
functionB(T arg){ do something; };
};
class Foo1 : public Foo<int>{
...
};
class Foo2 : public Foo<double>{
...
};
推荐答案
您实际上是在尝试不可能的事情.
You are actually attempting the impossible.
问题的核心很简单:virtual 和 template 不能很好地混合.
The very heart of the matter is simple: virtual and template do not mix well.
template是关于编译时代码生成的.您可以将其视为某种类型感知宏 + 一些元编程技巧.virtual是关于运行时决策,这需要一些工作.
templateis about compile-time code generation. You can think of it as some kind of type-aware macros + a few sprinkled tricks for meta programming.virtualis about runtime decision, and this require some work.
virtual 通常使用虚拟表(想想列出方法的表)来实现.方法的数量需要在编译时知道,并在基类中定义.
virtual is usually implemented using a virtual tables (think of a table which lists the methods). The number of methods need be known at compile time and is defined in the base class.
但是,根据您的要求,我们需要一个无限大小的虚拟表,其中包含我们尚未见过的类型的方法,并且只会在未来几年内定义......不幸的是,这是不可能的.
However, with your requirement, we would need a virtual table of infinite size, containing methods for types we haven't seen yet and that will only be defined in the years to come... it's unfortunately impossible.
如果有可能呢?
好吧,这没有意义.当我使用 int 调用 Foo2 时会发生什么?不是为了它!因此它打破了Foo2实现了IFoo中所有方法的原则.
Well, it just would not make sense. What happens when I call Foo2 with an int ? It's not meant for it! Therefore it breaks the principle that Foo2 implements all the methods from IFoo.
所以,如果你能说出真正的问题会更好,这样我们可以在设计层面而不是技术层面为你提供帮助:)
So, it would be better if you stated the real problem, this way we could help you at a design level rather than at a technical level :)
这篇关于在 C++ 中为抽象类模板创建接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)