C#-like properties in native C++?

I warn you, it is not fully compatible native C++: Microsoft-specific C++ only.

The Microsoft compiler allows you to use declspec(property), this way:

struct S {
   int i;
   void putprop(int j) { 
      i = j;
   }

   int getprop() {
      return i;
   }

   // here you define the property and the functions to call for it
   __declspec(property(get = getprop, put = putprop)) int the_prop;
};

int main() {
   S s;
   s.the_prop = 5;    // THERE YOU GO
   return s.the_prop;
}

cf Microsoft Documentation for more details: declspec(property).


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.


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;

Tags:

C++