Last active
January 1, 2016 03:29
-
-
Save hatsusato/8086293 to your computer and use it in GitHub Desktop.
snipet of union in C++03 for KMC Advent Calendar 2013
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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