引用类型之间的隐式转换

时间:2013-03-15 05:50:31

标签: c++ type-conversion

鉴于两个类A和B具有相同的数据布局(即只有函数不同,而不是成员),如何使引用类型可以隐式转换?

struct Storage
{
    uint32_t a, b;
};


class First : private Storage
{
    int32_t GetA() { return a; }
    int32_t GetB() { return b; }
};

class Second : private Storage
{
    int64_t GetA() { return a; }
    int64_t GetB() { return b; }
};


void FuncF(const First& first);
void FuncS(const Second& second);    

// I would like to be able to call like
int main()
{
    First f;
    Second s;

    FuncF(s);          // Conversion fails
    FuncS(f);          // Conversion fails

    return 0;
}

我可以将上述工作用于pass-by-copy,如果我使用class First : Second之类的继承,我可以通过一种方式进行转换。

(注意上面是一个人为的例子,你可以想象int32_t和int64_t返回类型是更复杂的类,可以从uint32_t构造)。

要明确:我对解决方法不感兴趣,我特别希望能够将First对象绑定到Second引用,反之亦然,依赖于事实数据是一样的。

FuncS(static_cast<Second&>(f));   // This works, is it standard (ie portable) 
                                  // and can I define the class so the cast is not necessary?

1 个答案:

答案 0 :(得分:1)

您可以使用Type Conversion Operator

所以Second需要一个成员函数的形式:Second :: operator First(); 同样在First中也是如此。这将进行隐式转换,无需进行类型转换。