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

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

问题描述

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

 模板< typename的T>
A级【T一;};模板< typename的T>
B类:公共A< T> {T B;};

和下面的类重presenting修改后的容器

 模板< typename的项目>
结构TItems {的typedef的std ::矢量<&项目GT;类型;};模板< typename的项目>
类ModCont
{
    私人的:
            类型名TItems<项目> ::类型的项目;
};

一个功能测试()的指针指向一个对象作为形式参数的容器:

 模板< typename的T>
无效测试(ModCont< A< T>> *吧){}

我想申请多态性与传递的B容器的方法测试:

  INT主(INT ARGC,CHAR *的argv [])
{  ModCont< A<双> > a_items;
  ModCont< B<双> > b_items;
  测试(安培; a_items); //作品
  测试(安培; b_items); //不工作
  返回0;
}

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

 模板< typename的对象>
无效测试(ModCont<对象> *吧){}

有什么办法如何使用功能,而不是多态的编译多态性(模板?)<​​/ P>

感谢您的帮助...


解决方案

嗯,首先,模板的的运行时多态性 - 他们是编译时多态

如果你想使用运行时多态性与这一点,你必须确保 ModCont&LT; B&LT; T&GT; &gt;将&LT; T&GT ModCont&LT派生。 &GT; - C时的方式处理++多态性不使这个默认值。或者,你可以有一切 ModCont&LT; T&GT; 一些常规 ModContBase ,虽然目前还不清楚如何将工作派生。

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

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

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

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

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?)

Thanks for your help...

解决方案

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

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天全站免登陆