Lazy Value

I wanted to replace a const int with a lazily evalueated int.  It had to be lazy evaluated as all that was needed to calculate it was not available when the class is instanciated but was available before the int was needed. I didn’t want to change the code that uses the int.  So, I made this class:

template <class T>
class CLazyValue
{
public:
   CLazyValue() : m_gotOffArse(false) {}
   operator T&() {return (m_gotOffArse ? m_value :
      (m_gotOffArse=true,GetOffArse(m_value),m_value));}
private:
   bool m_gotOffArse;
   T m_value;
   virtual void GetOffArse(T &val) = 0;
};

To use it, just derive and fill in GetOffArse.  Example:

class CTopOffset : public extra::CLazyValue
{
public:
   CTopOffset(CToolbarDrawerTabStyle &drawer) : m_drawer(drawer) {}
private:
   CToolbarDrawerTabStyle &m_drawer;
   virtual void GetOffArse(int &val);
}TAB_TOP_OFFSET;

Note the name of my const.  The int can be calculated from the m_drawer.  The great thing is, CLazyValue can be used whenever lazy evaluation is required.  I fear this may be rather obvious but it looks good.

Advertisements

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