Created
June 10, 2014 01:33
-
-
Save duckie/9ef85eb9d5ce2419d612 to your computer and use it in GitHub Desktop.
Private data member with automatic public read-only through an accessor.
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
#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