jlconlin
jlconlin

Reputation: 15064

Is there a C++11 equivalent to Python's @property decorator?

I really like Python's @property decorator; i.e.,

class MyInteger:
    def init(self, i):
        self.i = i

    # Using the @property dectorator, half looks like a member not a method
    @property
    def half(self):
         return i/2.0

Is there a similar construct in C++ that I can use? I could google it, but I'm not sure the terminology to search for.

Upvotes: 6

Views: 1373

Answers (1)

Svalorzen
Svalorzen

Reputation: 5618

Not saying that you should, and in fact, you should NOT do it. But here's a solution for giggles (it can probably be improved but hey it's just for fun):

#include <iostream>

class MyInteger;

class MyIntegerNoAssign {
    public:
        MyIntegerNoAssign() : value_(0) {}
        MyIntegerNoAssign(int x) : value_(x) {}

        operator int() {
            return value_;
        }

    private:
        MyIntegerNoAssign& operator=(int other) {
            value_ = other;
            return *this;
        }
        int value_;
        friend class MyInteger;
};

class MyInteger {
    public:
        MyInteger() : value_(0) {
            half = 0;
        }
        MyInteger(int x) : value_(x) {
            half = value_ / 2;
        }

        operator int() {
            return value_;
        }

        MyInteger& operator=(int other) {
            value_ = other;
            half.value_ = value_ / 2;
            return *this;
        }

        MyIntegerNoAssign half;
    private:
        int value_;
};

int main() {
    MyInteger x = 4;
    std::cout << "Number is:     " << x << "\n";
    std::cout << "Half of it is: " << x.half << "\n";

    std::cout << "Changing number...\n";

    x = 15;
    std::cout << "Number is:     " << x << "\n";
    std::cout << "Half of it is: " << x.half << "\n";

    // x.half = 3; Fails compilation..
    return 0;
}

Upvotes: 2

Related Questions