accessor_cast

From: JKop (NULL_at_NULL.NULL)
Date: 06/30/04


Date: Wed, 30 Jun 2004 16:48:02 GMT

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


Relevant Pages

  • Re: properly using unions.
    ... I want to save up some space by using unions. ... typedef struct svarrec { ... short int dtype; /* These 4 bytes also accessed as int using asint ... char spare; ...
    (comp.lang.c)
  • Re: Consideration on pointer declarations
    ... expecially complex ones with embedded typedef'd unions. ... typedef struct ... int serial_number; ...
    (comp.lang.c)
  • Re: Consideration on pointer declarations
    ... expecially complex ones with embedded typedef'd unions. ... typedef struct ... int serial_number; ...
    (comp.lang.c)
  • Re: An example of unions not being type safe?
    ... also say that an int is not typesafe because ... permitted to do with unions, ... easier mistake to make (or an easier thing to do deliberately if you ... don't mind undefined behavior). ...
    (comp.lang.c)
  • Union trouble
    ... I'm porting some code from a language that allows casual aliases to struct ... I can duplicate some of this with unions but the results look inelegant. ... int main ... {static vrec v; ...
    (comp.lang.c)