Archive for September, 2012

Simple little cashing variable or property trick

Posted in Uncategorized on September 13, 2012 by Crazy Eddie

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;

  bool cache_valid;
  T value;
  function<T()> calculator;

struct has_cache_value {
  cached_value<int> my_value;

    : my_value(bind(&has_cache_value::calculate, this))
  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(); }

  function<void(T)> assigner;
  function<T()> getter;

// use similarly.  Allows the calling of getter/setter using assignment syntax...
// = value;
// type value =;

Using wrappers like this for member variables can actually be used for all kinds of possibly useless stuff.