C#-like properties in native C++?

后端 未结 11 1903
南笙
南笙 2020-11-29 04:46

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

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

However, the above code does not actu

11条回答
  •  悲&欢浪女
    2020-11-29 05:31

    Moo-Juice's answer looks really cool, but has a drawback: you can't use these properties like normal expressions of type T, as you can in C#.

    For instance,

    • a.text.c_str() won't compile (‘class Property >’ has no member named ‘c_str’)
    • std::cout << a.text won't compile either (template argument deduction/substitution failed)

    I would suggest the following enhancement to template class Property:

    T& operator() ()
    {
        return _value;
    }
    T const& operator() () const
    {
        return _value;
    }
    

    Then you can access the property's members with (), such as:

     char const *p = a.text().c_str();
    

    And you can use the property in expressions where the type must be deduced:

    std::cout << a.text();
    

提交回复
热议问题