Creating an interface for an abstract class template in C++(在 C++ 中为抽象类模板创建接口)
问题描述
我有如下代码.我有一个抽象模板类 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++ 中为抽象类模板创建接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中为抽象类模板创建接口
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
