gpt4 book ai didi

c++ - 我能以某种巧妙的方式将 union 初始化为函数参数吗?

转载 作者:太空宇宙 更新时间:2023-11-04 15:06:50 25 4
gpt4 key购买 nike

我正在寻找一些我不确定是否存在的语法糖。这很难描述,所以我将提供一个例子:

#include <iostream>
using namespace std; // haters gonna hate

union MyUnion
{
float f;
unsigned int i;
// more types
};

unsigned int someFunction(MyUnion m)
{
return m.i;
}

int main()
{
unsigned int i = 10;
float f = 10.0;

// this is the syntactic sugar I'm looking to emulate
cout << someFunction(i) << endl; // automagically initializes unsigned int member
cout << someFunction(f) << endl; // automagically initializes float member
return 0;
}

我知道我可以定义一堆我的函数重载,在堆栈上声明 union ,初始化它,就像这样:

unsigned int someFunction(unsigned int i)
{
return i; // this is the shortcut case
}

unsigned int someFunction(float f)
{
MyUnion m = {f};
return m.i;
}

// more overloads for more types

但我希望有更好的方法。有吗?

最佳答案

你可以给 union 体一些构造函数:

union Jack
{
int a;
float f;

Jack(int a_) : a(a_) { }
Jack(float f_) : f(f_) { }
};

Jack pot(1);
Jack son(1.);

int main()
{
someFunction(Jack(100));
someFunction(100); // same, implicit conversion
}

关于c++ - 我能以某种巧妙的方式将 union 初始化为函数参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12308341/

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