Last active
December 23, 2020 08:47
-
-
Save blockspacer/49680b12351ac2c52ebcf13a84d0ae2c to your computer and use it in GitHub Desktop.
C++ example: operator overloading with template (strong numeric type)
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 <iostream> | |
#include <vector> | |
#include <concepts> | |
#include <iostream> | |
#include <type_traits> | |
template<typename Tag, typename T> | |
class StrongNum; | |
template<typename Tag, typename T> | |
class StrongNum | |
{ | |
public: | |
T m_val; | |
StrongNum(T val) | |
{ | |
m_val = val; | |
} | |
}; | |
template<typename Tag, typename RTag, typename T> | |
StrongNum<Tag, T> operator+(const StrongNum<Tag, T> m1, const StrongNum<RTag, T> m2) | |
{ | |
static_assert(std::is_same<Tag, RTag>::value, | |
"Unable to select underlying tag."); | |
return { m1.m_val + m2.m_val }; | |
} | |
template<typename TagType, typename Type, typename R | |
, typename std::enable_if< | |
!std::is_same<R, StrongNum<TagType,Type>>::value | |
>::type* = nullptr | |
> | |
StrongNum<TagType, Type> operator+(const StrongNum<TagType, Type> m, const R value) | |
{ | |
return { m.m_val + value }; | |
} | |
template<typename TagType, typename Type, typename R | |
, typename std::enable_if< | |
!std::is_same<R, StrongNum<TagType,Type>>::value | |
>::type* = nullptr | |
> | |
StrongNum<TagType, Type> operator+(const R value, const StrongNum<TagType, Type> m) | |
{ | |
return { m.m_val + value }; | |
} | |
int main() | |
{ | |
StrongNum<class TagA, int> m1{ 10 }; | |
StrongNum<class TagA, int> m2{ 8 }; | |
StrongNum<class TagA, int> m3{ 3 }; | |
StrongNum<class TagA, int> mFinal{ m1 + m2 + 5 + 8 + m3 + 16 }; | |
std::cout << "Result: (" << mFinal.m_val << ", " << | |
mFinal.m_val << ")\n"; | |
StrongNum<class TagA, int> m4 = (1 + m1); | |
StrongNum<class TagA, int> m5 = (m1 + 1); | |
StrongNum<class TagA, int> m6 = (m4 + m5); | |
std::cout << "Result: (" << m4.m_val << ")\n"; | |
std::cout << "Result: (" << m5.m_val << ")\n"; | |
std::cout << "Result: (" << m6.m_val << ")\n"; | |
StrongNum<class TagB, int> mB1{ 10 }; | |
StrongNum<class TagB, int> mB2{ 8 }; | |
StrongNum<class TagB, int> mB3{ 3 }; | |
StrongNum<class TagB, int> mB4 = (1 + mB1); | |
StrongNum<class TagB, int> mB5 = (mB1 + 1); | |
StrongNum<class TagB, int> mB6 = (mB4 + mB5); | |
std::cout << "Result: (" << mB4.m_val << ")\n"; | |
std::cout << "Result: (" << mB5.m_val << ")\n"; | |
std::cout << "Result: (" << mB6.m_val << ")\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment