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.

About these ads

3 Responses to “Simple little cashing variable or property trick”

  1. Unless I’m missing something, you never modify cache_valid, so I don’t think the cache functions as intended.

  2. [...] Sometimes, just because I can. « Simple little cashing variable or property trick [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 26 other followers

%d bloggers like this: