How to implement a discriminated union of a parameterless functor and its return value in C ++?

I know that I can use boost::variantand not ask this question. But use boost::variantincludes a lot of ugly code. In particular, visitors are dirty. So, without further ado ...

I wrote the following template class to implement a lazy evaluation of curry functions. (See my previous question for the entire snippet.)

template <typename> class curry;

template <typename _Res>
class curry< _Res() >
{
  public:
    typedef std::function< _Res() > _Fun;
    typedef _Res _Ret;

  private:
    _Fun _fun;

  public:
    explicit curry (_Fun fun)
    : _fun(fun) { }

    operator _Ret ()
    { return _fun(); }
};

So I want to update it to enable memoization. Conceptually, it is very simple. First of all, I have to replace:

private:
  _Fun _fun;

public:
  explicit curry (_Fun fun)
  : _fun(fun) { }

WITH

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) { }

. -, operator _Ret, , , memoized. -, , _evaluated _fun, _res. , .

-, _fun _res? , ?

operator _Ret ()
{
  if (!_evaluated) {
    _Fun fun = _fun;

    // Critical two lines.
    _fun.~_Fun();
    _res._Res(fun());

    _evaluated = true;
  }
  return _res;
}

-, _fun _res? , ?

~curry ()
{
   if (_evaluated)
     _res.~_Res();
   else
     _fun.~_Fun();
}
+3
1

, , .

new:

, A B, .

#include <iostream>
#include <cstring>

using namespace std;

struct foo {
  foo(char val) : c(val) {
    cout<<"Constructed foo with c: "<<c<<endl;
  }

  ~foo() {
    cout<<"Destructed foo with c: "<<c<<endl;
  }
  char c;
};

struct bar {
  bar(int val) : i(val) {
    cout<<"Constructed bar with i: "<<i<<endl;
  }

  ~bar() {
    cout<<"Destructed bar with i: "<<i<<endl;
  }

  int i;
};

template < size_t val1, size_t val2 >
struct static_sizet_max
{
   static const size_t value
     = ( val1 > val2) ? val1 : val2 ;
};

template <typename A, typename B>
struct unionType {
  unionType(const A &a) : isA(true)
  {
    new(bytes) A(a);
  }

  unionType(const B &b) : isA(false)
  {
    new(bytes) B(b);
  }

  ~unionType()
  {
    if(isA)
      reinterpret_cast<A*>(bytes)->~A();
    else
      reinterpret_cast<B*>(bytes)->~B();
  }

  bool isA;
  char bytes[static_sizet_max<sizeof(A), sizeof(B)>::value];
};

int main(int argc, char** argv)
{
  typedef unionType<foo, bar> FooOrBar;

  foo f('a');
  bar b(-1);
  FooOrBar uf(f);
  FooOrBar ub(b);

  cout<<"Size of foo: "<<sizeof(foo)<<endl;
  cout<<"Size of bar: "<<sizeof(bar)<<endl;
  cout<<"Size of bool: "<<sizeof(bool)<<endl;
  cout<<"Size of union: "<<sizeof(FooOrBar)<<endl;
}
0

All Articles