2
给定两个具有相同数据布局的类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;
}
我可以得到上面对于传拷贝工作,另外,如果我使用继承像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?
您可以将继承设为公共,然后将这两个类型的值绑定到对基的引用。 – 2013-03-15 05:59:25