Skip to content

Instantly share code, notes, and snippets.

@Jules-Baratoux
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jules-Baratoux/0e72f2b84b73aa37a20c to your computer and use it in GitHub Desktop.
Save Jules-Baratoux/0e72f2b84b73aa37a20c to your computer and use it in GitHub Desktop.
A C++ implementation of a C# like property accessors
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);
}
#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