Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
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
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 8:20 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC