在C ++中为抽象类模板创建一个接口 [英] Creating an interface for an abstract class template in C++

查看:217
本文介绍了在C ++中为抽象类模板创建一个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下。我有一个抽象模板类Foo和从模板的实例化派生的两个子类(Foo1和Foo2)。我希望在我的程序中使用指针,它可以指向Foo1或Foo2类型的对象,因此我创建了一个IFoo接口。



我的问题是我不确定如何在接口中包含functionB,因为它依赖于模板实例化。甚至可以通过界面使functionB可访问,或者我试图不可能?



非常感谢您的帮助。

  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> {
...
};


解决方案



事情的核心很简单: virtual template do不混合。




  • 模板是关于编译时代码生成。您可以将其视为某种类型感知的宏+元编程的几个技巧。

  • virtual 决定,这需要一些工作。



virtual 虚拟表(想一个列出方法的表)。



但是,根据你的要求,我们需要一个无限大的虚拟表,包含



如果可能的话?

如果是可能的话, p>

好吧,这没有意义。当我使用 int 调用 Foo2 时会发生什么?这不是为它!因此,它违反了 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.

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?

Thank you very much for your help.

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.

The very heart of the matter is simple: virtual and template do not mix well.

  • template is about compile-time code generation. You can think of it as some kind of type-aware macros + a few sprinkled tricks for meta programming.
  • virtual is about runtime decision, and this require some work.

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.

And if it were possible ?

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 ++中为抽象类模板创建一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆