Skip to content

Instantly share code, notes, and snippets.

@hatsusato
Last active January 1, 2016 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hatsusato/8086293 to your computer and use it in GitHub Desktop.
Save hatsusato/8086293 to your computer and use it in GitHub Desktop.
snipet of union in C++03 for KMC Advent Calendar 2013
template <typename T> // テンプレート共用体だって作れる
union U {
private:
struct {
bool is_allocated;
T i;
} si;
struct {
bool is_allocated;
T* p;
} sp;
void Clean() {
if (IsAllocated()) { delete sp.p; }
}
void Assign(const T& src, bool alloc) {
if (alloc) {
sp.is_allocated = true;
sp.p = new T(src);
} else {
si.is_allocated = false;
si.i = src;
}
}
public:
U(const T& src, bool alloc) { Assign(src, alloc); }
U(const U& src) { Assign(src.GetValue(), src.IsAllocated()); }
U& operator=(const U& rhs) {
if (IsAllocated() && rhs.IsAllocated()) {
*sp.p = *rhs.sp.p;
} else {
Clean();
Assign(rhs.GetValue(), rhs.IsAllocated());
}
return *this;
}
~U() { Clean(); }
T GetValue() const {
if (IsAllocated()) {
return *sp.p;
} else {
return si.i;
}
}
bool IsAllocated() const { return si.is_allocated; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment