C++,多态与函数参数的模板化 [英] C++, polymorphism vs. templatization of a function argument

查看:32
本文介绍了C++,多态与函数参数的模板化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个类 A 和 B,其中 A 是基类,B 是派生类:

There are two classes A and B, where A is the base class and B is the derived class:

template <typename T>
class A {T a;};

template <typename T>
class B: public A <T> {T b;};

以及以下表示修改后的容器的类

and the following class representing a modified container

template <typename Item>
struct TItems {typedef std::vector <Item> Type;};

template <typename Item>
class ModCont
{
    private:
            typename TItems <Item>::Type items;
};

函数 test() 具有指向 A 对象容器的指针作为形参:

A function test() has pointer to container of A objects as formal parameter:

template <typename T>
void test ( ModCont <A <T> > *it) {}

我想应用多态并将 B 的容器传递给方法测试:

I would like to apply polymorphism and pass container of B to the method test:

int main(int argc, char* argv[])
{

  ModCont < A <double> > a_items;
  ModCont < B <double> > b_items;
  test (&a_items); //Works
  test (&b_items); //Does not work
  return 0;
}

我发现的唯一方法是以这种方式模板化 test() 方法的参数:

The only way I found is to templatize a parameter of the test() method in this way:

template <typename Object>
void test ( ModCont <Object> *it) {}

有什么方法可以使用函数"多态而不是编译多态(模板?)

Is there any way how to use the the "function" polymorphism instead of the compile polymorphism (templates?)

感谢您的帮助...

推荐答案

嗯,首先,模板不是运行时多态——它们是编译时多态.

Uhm, first of all, templates are not runtime polymorphism -- they're compile-time polymorphism.

如果你想使用运行时多态性,你必须确保 ModCont> 派生自 ModCont<A<T>> -- C++ 处理多态的方式并没有使它成为默认值.或者,您可以让所有 ModCont<T> 派生自一些通用的 ModContBase,尽管目前还不清楚它是如何工作的.

If you want to use runtime polymorphism with this, you have to make sure that ModCont<B<T> > derives from ModCont<A<T> > -- the way C++ handles polymorphism does not make this the default. Alternatively, you could have all ModCont<T> derive from some general ModContBase, although it's unclear how that would work.

这篇关于C++,多态与函数参数的模板化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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