Skip to content

Instantly share code, notes, and snippets.

@duckie
Created June 10, 2014 01:33
Show Gist options
  • Save duckie/9ef85eb9d5ce2419d612 to your computer and use it in GitHub Desktop.
Save duckie/9ef85eb9d5ce2419d612 to your computer and use it in GitHub Desktop.
Private data member with automatic public read-only through an accessor.
#include <memory>
template <class Parent, typename T> class readable final {
friend Parent;
T value_;
operator T& () { return value_; }
public:
readable(T const& v) : value_(v) {}
readable(T&& v) : value_(std::move(v)) {}
T const& operator () () { return value_; }
};
struct test {
template <typename T> using attr = readable<test, T>;
attr<int> v = 0;
void inc() { ++v; }
};
int main() {
test t;
t.inc();
//t.v++; // Wont compile, though the argument is public !
return t.v();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment