View Single Post
Old Feb 10th, 2006, 1:26 PM   #1
Klipt
Hobbyist Programmer
 
Join Date: Dec 2005
Posts: 118
Rep Power: 0 Klipt is an unknown quantity at this point
Reseatable reference

The thread on references reminded me of a class I made ages ago, after reading about how to overload type-casts. It's sort of a syntactically-sugared pointer which acts like a reference but is reseatable.

I'm still not certain there isn't a bug in there somewhere which could make the whole thing blow up if treated incorrectly :p

#include <iostream>

using namespace std;

template <class t>
// a smart reference which can be redirected to refer to another variable
class ref
{
	private:
		// the internal pointer
		t* p;
	public:
		// assignment constructor
		ref(t& p2)
		{
			p = &p2;
		}
		// allows this ref to be treated as a C++ reference
		operator t&()
		{
			return (*p);
		}

		// change the variable this ref refers to
		// note: becuase of the above operator a ref can be used as a parameter
		friend void redirect (ref& a, t& p);
};

template <class t>
void redirect (ref<t>& a, t& p)
{
	a.p = &p;
}


int main()
{
	typedef ref<int> intRef;

	int i = 5, j = 10;

	cout << i << ' ' << j << endl;

	intRef ir = i;

	cout << ir << ' ' << j << endl;

	ir = 7;
	
	cout << i << ' ' << j << endl;

	redirect(ir, j); // ir.p = &j;

	cout << i << ' ' << ir << endl;

	ir = 3;
	
	cout << i << ' ' << j << endl;

	return 0;
}
Klipt is offline   Reply With Quote