2017-08-28 125 views
0

很长一段时间的读者,我想一个模板,返回不同的类

我在想,如果有人可以帮助我做我的代码简单一点使用模板返回从相同的基本派生不同的类。所以我可以调用类的函数而不是重写管理器类中的每个对象调用的函数。这里一个我目前的函数的例子电话:

void setLoopImage(AnimationManagerIndex & managerIndex, bool b) 
{ 
    switch (managerIndex.animationClass) 
    { 
     case ANIMATION_CLASS_BASE: 
     { 
      vAnimationObjectBase[managerIndex.index].setLoopImage(b); 
      break; 
     } 
     case ANIMATION_CLASS_MOVING: 
     { 
      vAnimationObjectMoving[managerIndex.index].setLoopImage(b); 
      break; 
     } 
     case ANIMATION_CLASS_MOVING_BEZIER: 
     { 
      vAnimationObjectMovingBezier[managerIndex.index].setLoopImage(b); 
      break; 
     } 
    } 
} 

我想创建一个返回像这样这些类模板函数:

template<class T> 
T & getAnimationObject(AnimationManagerIndex & managerIndex) 
{ 
    switch (managerIndex.animationClass) 
    { 
     case ANIMATION_CLASS_BASE: 
     { 
      return vAnimationObjectBase[managerIndex.index]; 
     } 
     case ANIMATION_CLASS_MOVING: 
     { 
      return vAnimationObjectMoving[managerIndex.index]; 
     } 
     case ANIMATION_CLASS_MOVING_BEZIER: 
     { 
      return vAnimationObjectMovingBezier[managerIndex.index]; 
     } 
    } 
} 

所以第一个函数将变为:

void setLoopImage(AnimationManagerIndex & managerIndex, bool b) 
{ 
    getAnimationObject(managerIndex).setLoopImage(b); 
} 
+3

你说这三个是从相同的基本衍生?然后你不需要模板。只需使用'Base&'作为返回类型即可。 – HolyBlackCat

+1

你的尝试有什么问题?你有什么实际的*问题?作为一个长期的读者,你应该有时间[阅读如何提出好问题](http://stackoverflow.com/help/how-to-ask),如果你还没有这样做,那么请这样做。 –

回答

1

你不需要这个模板。您可以通过创建一个定义了(纯)虚拟setLoopImage函数的基本(抽象)类来实现此目的。

class Base 
{ 
    virtual setLoopImage(bool b) = 0; 
}; 

推导以下每个类从上面的一个:vAnimationObjectBase,vAnimationObjectMoving和vAnimationObjectMovingBezier。

然后你getAnimationObject函数将返回基地&:

Base& getAnimationObject(AnimationManagerIndex & managerIndex) 
{ 
    switch (managerIndex.animationClass) 
    { 
     case ANIMATION_CLASS_BASE: 
     { 
      return vAnimationObjectBase[managerIndex.index]; 
     } 
     case ANIMATION_CLASS_MOVING: 
     { 
      return vAnimationObjectMoving[managerIndex.index]; 
     } 
     case ANIMATION_CLASS_MOVING_BEZIER: 
     { 
      return vAnimationObjectMovingBezier[managerIndex.index]; 
     } 
    } 
} 

每一个派生类将实现纯虚函数setLoopImage,你会调用它的派生类。

+2

为了进一步改进解决方案,只有*一个*对象集合,并且整个'switch'语句消失,剩下的只是一个'return'。 –

+0

@Someprogrammerdude同意。 – VuVirt

+0

谢谢你的回答,我现在就实施它。我打算将所有类的不同功能转移到一个类中,但是现在我将它们单独写出来以确保一切正常。我将如何去创建不同类的向量,而不用创建一个基础指针向量,而这些向量我都有不好的经验。 –

1

通常解决这个问题,是经典的继承:

struct drawable_interface { 
    virtual void setLoopImage(bool) = 0; 
}; 

drawable_interface & getAnimationObject(AnimationManagerIndex & managerIndex) { 
    /*Same code as before*/ 
} 
相关问题