J
JKop
I've written a cast to mimic the way unions work. Here it is,
"accessor_cast.hpp":
#ifndef INCLUDE_ACCESSOR_CAST
#define INCLUDE_ACCESSOR_CAST
template<typename TO, class FROM>
inline TO& accessor_cast(FROM& from)
{
return *(reinterpret_cast<TO*>(&from));
}
#endif
---
Firstly, here's a union sample file:
union SomeUnion
{
unsigned long a;
char b;
double c;
short d;
};
int main()
{
SomeUnion poo;
poo.a = 4000000000UL;
poo.b = 't';
poo.c = 48656.6435;
poo.d = 27;
}
----
Now here it is without unions:
#include <iostream>
#include "accessor_cast.hpp"
int main()
{
double poo;
accessor_cast<unsigned long>(poo) = 4000000000UL;
std::cout << "unsigned long: "
<< accessor_cast<unsigned long>(poo)
<< std::endl;
accessor_cast<char>(poo) = 't';
std::cout << "char: " << accessor_cast<char>(poo) << std::endl;
accessor_cast<double>(poo) = 48656.6435;
std::cout << "double: " << accessor_cast<double>(poo) << std::endl;
accessor_cast<short>(poo) = 27;
std::cout << "short: " << accessor_cast<short>(poo) << std::endl;
//Or if you like:
unsigned long& counter = accessor_cast<unsigned long>(poo);
counter = 4000000000UL;
std::cout << "counter == " << counter << std::endl;
}
I haven't bothered testing it with const variables.
-JKop
"accessor_cast.hpp":
#ifndef INCLUDE_ACCESSOR_CAST
#define INCLUDE_ACCESSOR_CAST
template<typename TO, class FROM>
inline TO& accessor_cast(FROM& from)
{
return *(reinterpret_cast<TO*>(&from));
}
#endif
---
Firstly, here's a union sample file:
union SomeUnion
{
unsigned long a;
char b;
double c;
short d;
};
int main()
{
SomeUnion poo;
poo.a = 4000000000UL;
poo.b = 't';
poo.c = 48656.6435;
poo.d = 27;
}
----
Now here it is without unions:
#include <iostream>
#include "accessor_cast.hpp"
int main()
{
double poo;
accessor_cast<unsigned long>(poo) = 4000000000UL;
std::cout << "unsigned long: "
<< accessor_cast<unsigned long>(poo)
<< std::endl;
accessor_cast<char>(poo) = 't';
std::cout << "char: " << accessor_cast<char>(poo) << std::endl;
accessor_cast<double>(poo) = 48656.6435;
std::cout << "double: " << accessor_cast<double>(poo) << std::endl;
accessor_cast<short>(poo) = 27;
std::cout << "short: " << accessor_cast<short>(poo) << std::endl;
//Or if you like:
unsigned long& counter = accessor_cast<unsigned long>(poo);
counter = 4000000000UL;
std::cout << "counter == " << counter << std::endl;
}
I haven't bothered testing it with const variables.
-JKop