Strong typing example
This file contains 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 <boost/operators.hpp> | |
// Mostly inspired by boosts strong typedef, but without the macros | |
// Resulting type is ordered just like the wrapped type | |
template <typename T> | |
class strong_typedef : boost::totally_ordered1<strong_typedef<T>, boost::totally_ordered2<strong_typedef<T>, T>> { | |
public: | |
strong_typedef() = default; | |
strong_typedef(const strong_typedef & t_) : | |
value(t_.value) {} | |
strong_typedef(const strong_typedef && t_) : | |
value(std::move(t_.value)) {} | |
explicit strong_typedef(const T val) : value(val) {}; | |
strong_typedef & operator=(const strong_typedef & rhs) { | |
value = rhs.value; | |
return *this; | |
} | |
strong_typedef & operator=(const T & rhs) { | |
value = rhs; | |
return *this; | |
} | |
operator const T& () const { | |
return value; | |
} | |
operator T& () { | |
return value; | |
} | |
bool operator==(const strong_typedef& rhs) const { | |
return value == rhs.value; | |
} | |
bool operator<(const strong_typedef& rhs) const { | |
return value < rhs.value; | |
} | |
private: | |
T value; | |
}; | |
using rows_t = strong_typedef<std::size_t>; | |
using cols_t = strong_typedef<std::size_t>; | |
void create(rows_t rows, cols_t cols) { | |
std::size_t combined = rows * cols; //using them like their original type | |
std::cout << combined << std::boolalpha << (rows < cols) << std::endl; | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
rows_t rows {10}; | |
cols_t cols {20}; | |
create(rows, cols); | |
create(rows_t {2}, cols_t {19}); | |
create(rows_t (4), cols_t (19)); | |
// create(2, 10); does not compile | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment