gpt4 book ai didi

c++ - 引用类型之间的隐式转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:28:34 24 4
gpt4 key购买 nike

<分区>

给定两个具有相同数据布局的类 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 对象绑定(bind)到 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?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com