(this is a bit similar to this question, and inspired by the C++11 FAQ on union but not exactly so...)
In the context of coding a Scheme-like interpreter in idiomatic C++11 Let's suppose I want a tagged union of a string, an int, and some closure. So I would probably code:
#include <string>
#include <new>
#include <memory>
#include <functional>
enum kind { nothing, string, integer, closure };
class Value {
enum kind k;
typedef std::string string_t;
union {
std::string str;
int num;
std::shared_ptr<std::function<Value(std::vector<Value>)>> clos;
};
public:
Value (const Value &v)
: k(none) {
switch (v.k) {
case none: break;
case string: new(&str)string_t(v.str); break;
case integer: num = v.num; break;
/// what about closure-s?
}
k = v.k;
};
Value& operator = (const Value&v) {
switch (v.k) {
case none: break;
case string: new(&str)string_t(v.str); break;
case integer: num = v.num; break;
/// what about closure-s?
}
k = v.k;
}
/// etc...
};
Now what about the closure
case? For the copy constructor and the assignment operator, I am tempted to code:
case closure: clos = v.clos; break;
But perhaps should I use a placement new
on a shared_ptr
?
I don't want to use Boost (or any non standard C++11 library) for that purpose.