如何在c ++中没有多态的情况下传递像多态的结构

时间:2014-11-11 05:16:47

标签: c++ inheritance polymorphism

我有一个函数接受一个只是数据持有者的结构(existing,existinghelper)的场景。但是处理这些数据的函数与这些数据紧密相关。现在我需要处理需要扩展结构的额外数据(to_be_extended,to_be_extended_helper)。实现这一目标的最佳方法是什么?

目前的代码如下所示:     结构存在     {     int a;     int b;     };

struct existinghelper
{
int aindex;
int bindex;
};

struct to_be_extended
{
existing e;
int c;
};

struct to_be_extended_helper
{
int aindex;
int bindex;
int cindex;
};

void fun1(existing& e)
{

existinghelper(e);
}

预期:我需要相同的代码(fun1)才能适用于扩展和现有结构。逻辑上如下

void fun1(existing& e ) // can be <to_be_extended & e> this should support both      existing and to_be_extended structure both.
{
existinghelper(e); // or to_be_extended_helper(ee);
//above line should support both existinghelper and to_be_extended_helper structure 

两者。     / *     //逻辑上它应该如下所示:

if(type == existing)

     make existinghelper object.
else
    make to_be_extended_helper object.

The problem is they are not polymorphic and are just data holders.
*/
} 

3 个答案:

答案 0 :(得分:1)

重载不同参数类型的函数:

void fun1(existing& e)
{
   ...
}

void fun1(to_be_extended& e)
{
   ...
}

如果你有很多代码对两个函数都是相同的,并且你试图避免代码重复,你可以将常用功能分解为函数模板。

template<typename T>
void identical_stuff(T& e)
{
    ...
}

void fun1(existing& e)
{
   ... non-identical stuff ...

   identical_stuff(e);
}

void fun1(to_be_extended& e)
{
   ... non-identical stuff ...

   identical_stuff(e);
}

答案 1 :(得分:0)

让他们成为多元化的首选。 如果不希望添加数据成员类型(可能是整数类型),那么如果type == 1 make existinghelper对象。 否则,如果type == 2 make to_be_extended_helper object。

答案 2 :(得分:0)

使 to_be_extended 扩展现有,并添加标记。

struct existing
{
    int a, b;
    bool isBase;
    existing():isBase(true){}
}
struct to_be_extended : public existing
{
    int c;
    to_be_extended():isBase(false){}
}
func(existing& e)
{
    if(e.isBase)
        ...
    else
        ...
}