C++ で新潟
いわゆる読めるけど書けないメンバ変数。
ちょっと書いてみた。
[ソース]
#include <iostream> #include <type_traits> #include <string> template<typename Class, typename Type, Type Class::*PtrToMember> struct property{ property(Class& self) : self(self){} operator Type const&() const{ return get(); } Type const& get() const{ return self.*PtrToMember; } private: Class& self; }; template<typename Class, typename Type, Type Class::*PtrToMember> std::ostream& operator <<(std::ostream& os, property<Class, Type, PtrToMember> member){ return os << member.get(); } struct X{ private: int value_; std::string str_; public: typedef decltype(&X::value_) hoge; X(std::string str) : value_(0), str_(str){} property<X, int, &X::value_> value = *this; property<X, std::string, &X::str_> str = *this; void set_value(int n){ value_ = n; str_ = "mado"; } }; int main(){ X x("homu"); std::cout << x.value << std::endl; std::cout << x.str << std::endl; // x.value = 10; // error x.set_value(42); std::cout << x.value << std::endl; std::cout << x.str << std::endl; return 0; }