0

I have union called f defined as

union uf {
  unsigned u;
  float f;
}

I have two functions.

void inner_function(uf& in) {
  //modify in
}

void outer_function(unsigned& val) {
  inner_function(static_cast<uf> (val));
}

can someone please explain me why I am getting "invalid initialization of non-const reference of type 'uf&' from a temporary of type 'uf' error.

So I understand that I can't cast this. So how would someone can fix this issue? I know this works

void outer_function(unsigned& val) {
  uf a; 
  a.u = val;
  inner_function(a);
  val = a.u;
}

anything more efficient?

4

1 回答 1

1

static_cast<T>(x)where Tis not a reference type的结果是给定类型的右值。您不能将非常量引用绑定到rvalue,从而导致错误。

你可以做reinterpret_cast<uf&>让编译器高兴,但你可能试图以错误的方式做某事,你很可能会在某处的那段代码中遇到未定义的行为。

有趣的问题是,你认为强制转换为 union 类型会对你有什么帮助?(也就是说,您要解决的原始问题是什么)

于 2013-08-22T16:57:43.997 回答