簡體   English   中英

具有相同布局的不同類型之間的C ++轉換

[英]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並單獨復制成員是一種解決方案,但這種情況將在許多函數中的許多不同結構對中發生。 不幸的是,修改ABFunc1的定義以及Func2的簽名都是不可能的。

據我所知,結構AB在內存中的表示方式相同。 在兩個這樣的結構之間進行轉換而又不違反嚴格的別名的最快方法是什么?

您可以強制轉換指針。 但是沒有必要。 由於您要傳遞值,因此無論如何都需要創建正確類型的實例,所以只要

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM