Simple little cashing variable or property trick
The trick I talked about earlier regarding exposing a single ‘variable’ to a friend can be used for other things as well. How useful I’ll leave you to determine. These ideas can likely be enhanced quite a bit to perform for more general solutions but I’ve not yet spent much time on them. Here goes:
Cached variable…
template < typename T >
struct cached_value {
cached_value(function<T()> c) : calculator(c) {}
void invalidate() { cache_valid = false; }
T operator() () {
if (!cache_valid) {
value = calculator();
cache_valid = true;
}
return value;
}
private:
bool cache_valid;
T value;
function<T()> calculator;
};
struct has_cache_value {
cached_value<int> my_value;
has_cache_value()
: my_value(bind(&has_cache_value::calculate, this))
{}
private:
int calculate() { return 5; }
Mimicking “properties” (not sure why you would, but just because I can…)
// I didn't do a test on this but am fairly confident it works, or is at least close.
template < typename T >
struct property {
property(function<void(T)> ass, function<T()> get)
: assigner(ass)
, getter(get)
{}
property& operator = (T t) { assigner(t); }
operator (T) () const { return getter(); }
private:
function<void(T)> assigner;
function<T()> getter;
};
// use similarly. Allows the calling of getter/setter using assignment syntax...
// object.property = value;
// type value = object.property;
Using wrappers like this for member variables can actually be used for all kinds of possibly useless stuff.
September 13, 2012 at 1:56 am
Unless I’m missing something, you never modify cache_valid, so I don’t think the cache functions as intended.
September 13, 2012 at 2:39 am
Yeah, oops. Edit error when typing it in to the blog. Should have copy/pasted.
December 29, 2012 at 1:54 am
[...] Sometimes, just because I can. « Simple little cashing variable or property trick [...]