可能性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;
}
なぜ専門性は「悪いハック」だと思いますか? C++では "静的if"というものはありませんので、別のテンプレートを定義する以外の方法はありません。私は間違っているかもしれません。 –
あなたは 'selectMemeber(a、M)= selectMember(b、M);'を意味すると思います。 – Philipp
@Philipp、はい、ありがとうございます。編集されました。 – user1476999