可能性 1
您可以使用简单的结构来选择成员,而不是使用枚举:
typedef short int16_t;
typedef long int32_t;
union Union {
int16_t i16;
int32_t i32;
};
struct ActiveMemberI16 {};
struct ActiveMemberI32 {};
template <typename M>
void doSomething(Union& a, Union b) {
selectMember(a, M()) = selectMember(b, M());
// this would be exactly (not equivalent) the same
// that a.X = b.X depending on T.
}
int16_t& selectMember(Union& u, ActiveMemberI16)
{
return u.i16;
}
int32_t& selectMember(Union& u, ActiveMemberI32)
{
return u.i32;
}
int main(int argc, char* argv[])
{
Union a,b;
a.i16 = 0;
b.i16 = 1;
doSomething<ActiveMemberI16>(a,b);
std::cout << a.i16 << std::endl;
b.i32 = 3;
doSomething<ActiveMemberI32>(a,b);
std::cout << a.i32 << std::endl;
return 0;
}
这需要为联合中的每个成员定义一个结构和一个 selectMember 方法,但至少您可以在许多其他函数中使用 selectMember。
请注意,我将参数转换为引用,如果不合适,您可以调整它。
可能性 2
通过将联合指针转换为所需的类型指针,您可以使用单个 selectMember 函数。
typedef short int16_t;
typedef long int32_t;
union Union {
int16_t i16;
int32_t i32;
};
template <typename T>
T& selectMember(Union& u)
{
return *((T*)&u);
}
template <typename M>
void doSomething(Union& a, Union b) {
selectMember<M>(a) = selectMember<M>(b);
// this would be exactly (not equivalent) the same
// that a.X = b.X depending on T.
}
int _tmain(int argc, _TCHAR* argv[])
{
Union a,b;
a.i16 = 0;
b.i16 = 1;
doSomething<int16_t>(a,b);
std::cout << a.i16 << std::endl;
b.i32 = 100000;
doSomething<int32_t>(a,b);
std::cout << a.i32 << std::endl;
return 0;
}