Sign in to follow this  
soconne

__declspec property feature in Visual C++

Recommended Posts

So I just discovered __declspec property and how it can alleviate all the headaches of not having class property accessors in C++, or having to create bloated class objects simply for wanting an integer value property. http://msdn.microsoft.com/en-us/library/yhfk0thd(VS.80).aspx Now I realize this is a Microsoft extension for C++, but is anything similar to this supported by other compilers, especially gcc, mingw, ect...? Anything that's cross-platform?

Share this post


Link to post
Share on other sites
Personally, I would just stick with using set/get functions rather than touch that ugly property syntax ;D

Each to their own though, so here's my attempt at a portable property class:
template<class T, class P, const T& (P::*get)(), void (P::*put)(const T&)>
class Property
{
public:
Property( P& parent ) : parent(parent) {} P& parent;
operator const T&() const { return (parent.*get)(); }
Property<T,P,get,put>& operator=( const T& rhs ) { (parent.*put)(rhs); return *this; }
private:
Property( const Property<T,P,get,put>& );
Property<T,P,get,put>& operator=( const Property<T,P,get,put>& );
};
It's very clunky itself; you've got to initialize the property using a reference to the object that set/get will be called on, and no operators can be used (besides casting to T, and assigning from T). At least this isn't compiler specific though.

And a test/example:
class Test
{
public:
Test() : prop(*this), i(0) {}
const int& GetInt() { return i; }
void SetInt( const int& in ) { i = in; }
Property<int,Test,&Test::GetInt,&Test::SetInt> prop;
private:
int i;
};
void PropertyTest()
{
Test obj;
int i = obj.prop;
ASSERT( i == 0 );
obj.prop = 10;
i = obj.prop;
ASSERT( i == 10 );
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this