Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

c - Does C11 have C#-style properties? - Stack Overflow #11934

Open
guevara opened this issue Dec 16, 2024 · 0 comments
Open

c - Does C11 have C#-style properties? - Stack Overflow #11934

guevara opened this issue Dec 16, 2024 · 0 comments

Comments

@guevara
Copy link
Owner

guevara commented Dec 16, 2024

c++ - Does C++11 have C#-style properties? - Stack Overflow



https://ift.tt/iCEqlbB






C++ doesn't have this built in, you can define a template to mimic properties functionality:

template <typename T>
class Property {
public:
    virtual ~Property() {}  //C++11: use override and =default;
    virtual T& operator= (const T& f) { return value = f; }
    virtual const T& operator() () const { return value; }
    virtual explicit operator const T& () const { return value; }
    virtual T* operator->() { return &value; }
protected:
    T value;
};

To define a property:

Property<float> x;

To implement a custom getter/setter just inherit:

class : public Property<float> {
    virtual float & operator = (const float &f) { /*custom code*/ return value = f; }
    virtual operator float const & () const { /*custom code*/ return value; }
} y;

To define a read-only property:

template <typename T>
class ReadOnlyProperty {
public:
    virtual ~ReadOnlyProperty() {}
    virtual operator T const & () const { return value; }
protected:
    T value;
};

And to use it in class Owner:

class Owner {
public:
    class : public ReadOnlyProperty<float> { friend class Owner; } x;
    Owner() { x.value = 8; }
};

You could define some of the above in macros to make it more concise.







via Stack Overflow

December 16, 2024 at 02:56PM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant