accessor_cast

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
 
B

bartek

JKop said:
I've written a cast to mimic the way unions work.
(...)

Unions are not meant as a tool for casting between types. "Casting through
a union" is just a method of fooling the compiler so it doesn't issue an
error message.
 
J

JKop

bartek posted:
(...)

Unions are not meant as a tool for casting between types. "Casting
through a union" is just a method of fooling the compiler so it doesn't
issue an error message.

I'm using it to access a certain piece of memory differently.


-JKop
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,476
Latest member
blackwatermelon

Latest Threads

Top