有没有相当于 Python @property装饰器的 C++11?
Is there a C++11 equivalent to Python's @property 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++中,我可以使用?我可以谷歌一下,但我不确定要搜索的术语。
不是说你应该这样做,事实上,你不应该这样做。但这里有一个解决傻笑的办法(它可能可以改进,但嘿,这只是为了好玩):
#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;
}
相关文章:
- 相当于LocaleMatcher的ICU4C
- 相当于 pybind11 中的 boost::p ython py::scope().attr()
- C++相当于整数的 #define
- 什么相当于 Kotlin 上的C++指针?
- 相当于 Java 中的C++结构
- 霓虹灯中的_mm_hadd_ps相当于什么?
- 相当于 VirtualAlloc() 的_set_new_handler?
- 对于 poco 库来说,Boost_USE_STATIC_LIBS相当于什么?
- 什么 clang-format 相当于 rustfmt 的 indent_style=Block?
- 犰狳相当于 A(find(A<0)) = 0
- 相当于C++运算符中的 Python
- C++ C 的双指针相当于什么?
- 相当于Linux fifo的Windows
- 相当于numpy.exexpand_dims()和numpy.contenate()的C++
- 相当于旧版C++的 C++11 unordered_map
- "new int[8]()"相当于C++11中的"new int[8]{}"吗?
- 相当于Boost has_dereference的C++11 std
- C++11 相当于 Java 的实例是什么
- 有没有相当于 Python @property装饰器的 C++11?
- 相当于c++ 11中的boost shared_mutex