title: How to implement a discriminated union of a parameterless functor and its return value in C++?
body: <p>I know I could use <code>boost::variant</code> and avoid having to ask this question. But using <code>boost::variant</code> involves a lot of ugly code. In particular, visitors are messy. So, without further ado...</p>
  
  <p>I have written the following templated class to implement lazy evaluation of curried functions. (See <a href="https://stackoverflow.com/questions/10432001/deep-function-currying-in-c-using-template-metaprogramming">my previous question</a> for the whole snippet.)</p>
  
  <pre><code>template &lt;typename&gt; class curry;
  
  template &lt;typename _Res&gt;
  class curry&lt; _Res() &gt;
  {
    public:
      typedef std::function&lt; _Res() &gt; _Fun;
      typedef _Res _Ret;
  
    private:
      _Fun _fun;
  
    public:
      explicit curry (_Fun fun)
      : _fun(fun) { }
  
      operator _Ret ()
      { return _fun(); }
  };
  </code></pre>
  
  <p>So I want to update it to include memoization. Conceptually, it is very simple. First of all, I have to replace:</p>
  
  <pre><code>private:
    _Fun _fun;
  
  public:
    explicit curry (_Fun fun)
    : _fun(fun) { }
  </code></pre>
  
  <p>With:</p>
  
  <pre><code>private:
    bool _evaluated; // Already evaluated?
    union
    {
        _Fun _fun;   // No
        _Res _res;   // Yes
    };
  
  public:
    explicit curry (_Fun fun)
    : _evaluated(false), _fun(fun) { }
  
    explicit curry (_Res res)
    : _evaluated(true), _res(res) { }
  </code></pre>
  
  <p>But there are two things left. First, I have to update <code>operator _Ret</code> so that, if it performs the lazy evaluation, then the result actually gets memoized. Second, I have to add a destructor so that, depending on the value of <code>_evaluated</code>, either <code>_fun</code> or <code>_res</code> gets destroyed. And here is where I am not quite sure about how to do things.</p>
  
  <p>First, is this the correct way to replace <code>_fun</code> with <code>_res</code>? If not, how should I do it?</p>
  
  <pre><code>operator _Ret ()
  {
    if (!_evaluated) {
      _Fun fun = _fun;
  
      // Critical two lines.
      _fun.~_Fun();
      _res._Res(fun());
  
      _evaluated = true;
    }
    return _res;
  }
  </code></pre>
  
  <p>Second, is this the correct way to selectively destroy <code>_fun</code> or <code>_res</code>? If not, how should I do it?</p>
  
  <pre><code>~curry ()
  {
     if (_evaluated)
       _res.~_Res();
     else
       _fun.~_Fun();
  }
  </code></pre>