Last active
August 29, 2015 14:03
-
-
Save Jules-Baratoux/0e72f2b84b73aa37a20c to your computer and use it in GitHub Desktop.
A C++ implementation of a C# like property accessors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Obj | |
{ | |
accessor(char) | |
{ | |
get { | |
std::cout << "get: " << value << std::endl; | |
} | |
set { | |
std::cout << "set: " << value << std::endl; | |
} | |
} c; | |
accessor(int) | |
{ | |
get { | |
std::cout << "get: " << value << std::endl; | |
} | |
set { | |
std::cout << "set: " << value << std::endl; | |
} | |
} i; | |
}; | |
int main() | |
{ | |
Obj obj; | |
obj.c = 'c'; // calls obj.c.set | |
print(obj.c); // calls obj.c.get | |
obj.i = 42; | |
print(obj.i); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define accessor_class(accessor, type) \ | |
class accessor \ | |
{ \ | |
type value; \ | |
\ | |
accessor(const accessor&) = delete; \ | |
type& operator=(const accessor&) = delete; \ | |
\ | |
public: \ | |
template <typename... Args> \ | |
accessor(Args... args) : value() {} \ | |
\ | |
inline operator const type& (void) const \ | |
{ \ | |
__get(); \ | |
return value; \ | |
} \ | |
\ | |
inline accessor& operator=(const type & rhs) \ | |
{ \ | |
value = rhs; \ | |
__set(); \ | |
return *this; \ | |
} \ | |
enum | |
#define accessor_class_definition(NAME, ID, TYPE) accessor_class(NAME##ID, TYPE) | |
#define accessor_classname_gen(NAME, ID, TYPE) accessor_class_definition(NAME, ID, TYPE) | |
#define accessor(TYPE) accessor_classname_gen(accessor, __COUNTER__, TYPE) | |
#define get __dummy}; private: \ | |
inline void __get (void) const | |
#define set \ | |
inline void __set(void) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment