是否有一个C ++ 11等同于Python的@property装饰器?

时间:2014-05-22 21:28:45

标签: python c++ c++11 decorator

我真的很喜欢Python的@property装饰器;即,

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

我可以使用C ++中的类似构造吗?我可以谷歌,但我不确定要搜索的术语。

1 个答案:

答案 0 :(得分:1)

不是说你应该,事实上,你不应该这样做。但这里有一个解决咯咯笑的方法(它可能会有所改进,但嘿,它只是为了好玩):

#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;
}