我可以用一些巧妙的方法将并集初始化为函数参数吗
Can I initialize a union as a function argument in some clever way?
我正在寻找一点我不确定是否存在的语法糖。这很难描述,所以我将提供一个例子:
#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;
}
我知道我可以定义我的函数的一堆重载,在堆栈上声明并集,初始化它,比如:
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 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
}
相关文章:
- 正在初始化函数指针的constexpr数组
- 我应该在C++中使用构造函数还是初始化函数
- 使用 extern const 初始化函数
- 初始化函数中的静态变量,而不是在文件开始时
- 如何初始化函数中指针数组的大小
- 正在初始化初始化函数中的静态类成员
- call_once初始化函数
- SWIG + CMAKE:缺少初始化函数
- 如何创建在 c++ 中只读取一次的初始化函数
- 类内的强制初始化函数
- 使用元编程在编译时初始化函数数组
- 数组初始化函数:将数组作为指针传递:C++
- 从nodejs模块初始化函数报告失败
- 导入错误:动态模块未定义初始化函数
- 大括号初始化函数指针数组:从 'void (*(*)())()' 到 'void (*)()' 的转换无效
- 奇怪的行为,用 int 初始化函数指针
- 使用 init_seg 调用初始化函数
- 正在初始化函数内部的std::数组
- 初始化函数内部的指针.它是如何工作的
- JNI初始化函数以及缓存类和字段