Snippets

Neural Outlet Fun with Unions

Created by Neural Outlet last modified
#include <cstdint>
#include <cstdio>
#include <new>

/*
 * A function to take two pointers and:
 *    * create a new pointer to union of their types
 *    * assign it the value of 'foo'
 *    * delete the original pointers
 *    * reassign them to both point to the union
*/
template<typename F, typename B>
bool membind(F *&foo, B *&bar)
{
	if (sizeof(foo) != sizeof(bar))
		return false;

	F temp = (*foo);
	delete foo;
	delete bar;

	union uni_t { F foo; B bar; };
	uni_t *result = new uni_t;
	foo = &(result->foo);
	bar = &(result->bar);
	new (foo) F(temp);

	return true;
}

/*
 * Creating a pointer to store a hex colour value
 * and a struct rgba value then binding them together
*/
int main()
{
	struct Pixel
	{
		uint8_t a;
		uint8_t b;
		uint8_t g;
		uint8_t r;
	};

	uint32_t *colour = new uint32_t(0xFF00FFFF);
	Pixel *pixel = new Pixel{0};
	

	printf("[%p]: %0x\n[%p]: %d %d %d %d\n", colour, (*colour),
	       pixel, pixel->r, pixel->g, pixel->b, pixel->a);

	printf("\nCalling membind..\n\n");
	if (membind(colour, pixel))
	{
		printf("[%p]: %0x\n[%p]: %d %d %d %d\n", colour, (*colour),
		       pixel, pixel->r, pixel->g, pixel->b, pixel->a);
	}

	return 0;
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.