[英]C++ conversion between different types with the same layout
如果我有兩個定義相同的結構,那么在它們之間進行轉換的最佳方法是什么?
struct A { int i; float f; };
struct B { int i; float f; };
void Func1(A);
void Func2(B);
Func2
需要調用Func1
通過采取B
參數,使其成為A
。 它看起來像:
void Func2(B b) { Func1( (A) b); } //Obviously invalid cast
雖然創建A
並單獨復制成員是一種解決方案,但這種情況將在許多函數中的許多不同結構對中發生。 不幸的是,修改A
, B
或Func1
的定義以及Func2
的簽名都是不可能的。
據我所知,結構A
和B
在內存中的表示方式相同。 在兩個這樣的結構之間進行轉換而又不違反嚴格的別名的最快方法是什么?
您可以強制轉換指針。 但是沒有必要。 由於您要傳遞值,因此無論如何都需要創建正確類型的實例,所以只要
void f2( B b ) { f1( A{ b.i, b.f } ); }
簡單。
當簡單的類型安全代碼可以滿足您的需求時,不要考慮強制類型轉換。
您可以在Func2()的定義中代理類BA:
#include <iostream>
struct A { int i; float f; };
struct B { int i; float f; };
struct BA
{
const B &b_;
BA(const B &b)
: b_(b) {}
operator A() const
{
A a = {b_.i, b_.f};
return a;
}
};
void Func1(A a) { std::cout << a.i << " " << a.f << std::endl;};
void Func2(B b) { Func1(BA(b)); }
int main()
{
B b = {2, 42.};
Func2(b);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.