C#-like properties in native C++?

后端 未结 11 1891
南笙
南笙 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:26

    By using std::function you can get pretty close. Featurewise everything is here.

    First create the templated Property class:

    #include 
    
    template
    class Property
    {
        std::function _get;
        std::function _set;
    public:
        Property(
            std::function get,
            std::function set)
            : _get(get),
              _set(set)
        { }
    
        Property(
            std::function get)
            : _get(get),
              _set([](const unsigned int&){})
        { }
    
        operator T () const { return _get(); }
        void operator = (const T& t) { _set(t); }
    };
    

    Use the Property in a class by creating a get and a set method similar to what you would in do C#:

    class Test
    {
    private:
        std::string  _label;
    
    public:
        Property Label = Property
        (
            [this]()->std::string
            {
                return this->_label;
            },
            [this](const std::string& value)
            {
                this->_label = value;
            }
        );
        Property LabelSize = Property
        (
            [this]()->unsigned int
            {
                return this->_label.size();
            }
        );
    };
    

    Testing this code:

    Test test;
    test.Label = "std functional";
    
    std::cout << "label      = " << std::string(test.Label) << std::endl
              << "label size = " << int(test.LabelSize) << std::endl;
    

    will output

    label      = std functional
    label size = 14
    

    I think this is as syntactic-sugar-coated as you can get it in c++ :)

提交回复
热议问题