Created
September 29, 2017 11:26
-
-
Save nmmmnu/596adf8f0475f5a838d28094015599a1 to your computer and use it in GitHub Desktop.
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
#include <iosfwd> | |
#include <utility> // std::forward | |
template<typename T, class TAG> | |
class StrongTypedef{ | |
private: | |
using ST = StrongTypedef; | |
T v; | |
public: | |
StrongTypedef() = default; | |
template<typename UT> | |
explicit StrongTypedef(UT &&v) : v(std::forward<UT>(v)){} | |
public: | |
// we want this to be ugly | |
const T &getValue() const{ | |
return v; | |
} | |
T &getValue(){ | |
return v; | |
} | |
public: | |
bool operator == (const ST& other) const { return v == other.v; } | |
bool operator != (const ST& other) const { return v != other.v; } | |
bool operator <= (const ST& other) const { return v <= other.v; } | |
bool operator >= (const ST& other) const { return v >= other.v; } | |
bool operator > (const ST& other) const { return v > other.v; } | |
bool operator < (const ST& other) const { return v < other.v; } | |
public: | |
ST operator + (const ST& other) const { return ST{ v + other.v }; } | |
ST operator - (const ST& other) const { return ST{ v - other.v }; } | |
ST operator * (const ST& other) const { return ST{ v * other.v }; } | |
ST operator / (const ST& other) const { return ST{ v / other.v }; } | |
public: | |
ST& operator *= (const ST& other){ v *= other.v; return *this; } | |
ST& operator /= (const ST& other){ v /= other.v; return *this; } | |
ST& operator += (const ST& other){ v += other.v; return *this; } | |
ST& operator -= (const ST& other){ v -= other.v; return *this; } | |
public: | |
ST operator ++ () const { ST other = &this; ++other; return other; } | |
ST operator -- () const { ST other = &this; ++other; return other; } | |
ST& operator ++ (){ ++v; return *this; } | |
ST& operator -- (){ --v; return *this; } | |
public: | |
ST operator + () const { return +v; } | |
ST operator - () const { return -v; } | |
public: | |
friend std::ostream& operator << (std::ostream& os, const ST &st){ | |
os << st.v; | |
return os; | |
} | |
}; | |
#include <iostream> | |
int main(){ | |
struct LevelTag{}; | |
using Level = StrongTypedef<int, LevelTag>; | |
Level a{ 4 }; | |
Level b{ 12 }; | |
// error | |
// auto x = a + 5; | |
++a; | |
Level c = a * b; | |
std::cout << a << '\n'; | |
return c.getValue(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment