我能以一种聪明的方式将union作为函数参数初始化吗?

时间:2012-09-06 21:02:33

标签: c++ initialization unions

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

#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

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

1 个答案:

答案 0 :(得分:8)

你可以给联盟一些构造函数:

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
}