Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#-like properties in native C++?

Tags:

In C# / .NET you can do something like this:

someThing.text = "blah"; String blah = someThing.text; 

However, the above code does not actually interact with the someThing's text String directly, it uses a get and set property. Similarly, read-only properties can be used.

Is there a way to do something similar in native C++? (not C++ .NET)

like image 415
jmasterx Avatar asked Nov 19 '10 12:11

jmasterx


2 Answers

WARNING: This is a tongue-in-cheek response and is terrible!!!

Yes, it's sort of possible :)

template<typename T> class Property { private:     T& _value;  public:     Property(T& value) : _value(value)     {     }   // eo ctor      Property<T>& operator = (const T& val)     {         _value = val;         return *this;     };  // eo operator =      operator const T&() const     {         return _value;     };  // eo operator () }; 

Then declare your class, declaring properties for your members:

class Test { private:     std::string _label;     int         _width;  public:     Test() : Label(_label)            , Width(_width)     {     };      Property<std::string> Label;     Property<int>         Width; }; 

And call C# style!

Test a; a.Label = "blah"; a.Width = 5;  std::string label = a.Label; int width = a.Width; 
like image 97
Moo-Juice Avatar answered Sep 18 '22 07:09

Moo-Juice


In .NET properties are syntactic sugar for the real get and set functions which are emitted behind the scenes (in fact they are more than syntactic sugar because properties are emitted in the resulting IL and could be used with Reflection). So in C++ you would need to explicitly write those functions as there's no such notion as property.

like image 20
Darin Dimitrov Avatar answered Sep 21 '22 07:09

Darin Dimitrov