I posted on the my Italian blog a post where I explain a way to emulate the property construct of the CBuilder in the C++ standard. Just as reference here I report a class declaration called CPanel using the CBuilder syntax for property definition:
class CPanel
{
private:
int m_Width; // Private member for Width property
int m_Height; // Private member for Height property
protected:
void __fastcall SetWidth(int AValue); // Set the Width property
int __fastcall GetWidth(); // Get the Width property
void __fastcall SetHeight(int AValue);// Set the Height property
int __fastcall GetHeight(); // Get the Height property
public:
CPanel()
{
}
__property int Width = {read=GetWidth, write=SetWidth};
__property int Height = {read=GetHeight, write=SetHeight};
}
As you see the the syntax is very simple, you can define the private members m_Height and m_Width, the protected setter and getter methods and finally you can define your properties using the special keyword called __property. The following code shows you how to use the properties in your main function:
int main()
{
CPanel Panel;
Panel.Width = 10;
Panel.Height = 10;
int TmpWidth = Panel.Width;
int TmpHeight = Panel.Height;
}
We can emulate the same syntax defining a template class for our generic property, the following code shows a definition of a template class for this purpose:
template<typename owner_t,
typename prop_t,
void (owner_t::*setter)(prop_t),
prop_t (owner_t::*getter)()>
class CProperty
{
public:
// Constructor
CProperty(owner_t* owner){m_owner = owner;}
// op = overloading
void operator=(prop_t value)
{
return (m_owner->*setter)(value);
}
// op type overloading
operator prop_t()
{
return (m_owner->*getter)();
}
private:
prop_t* m_owner;
}
Thanks the above template we can redefine our CPanel class using the standard c++ language:
class CPanel
{
private:
int m_Width; // Private member for Width property
int m_Height; // Private member for Height property
protected:
void SetWidth(int AValue); // Set the Width property
int GetWidth(); // Get the Width property
void SetHeight(int AValue);// Set the Height property
int GetHeight(); // Get the Height property
public:
CPanel()
:Width(this), Height(this)
{
}
CProperty<CPanel, int, SetWidth, GetWidth> Width;
CProperty<CPanel, int, SetHeight, GetHeight> Height;
}
As you can see the syntax is very similar, but now it is standard. You can use the new CPanel class like previous main function:
int main()
{
CPanel Panel;
Panel.Width = 10;
Panel.Height = 10;
int TmpWidth = Panel.Width;
int TmpHeight = Panel.Height;
}
Here is a link to the full post (in Italian language)