Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.