diff options
Diffstat (limited to '')
-rw-r--r-- | operator-overloading.cpp | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/operator-overloading.cpp b/operator-overloading.cpp new file mode 100644 index 0000000..92ef2d8 --- /dev/null +++ b/operator-overloading.cpp @@ -0,0 +1,62 @@ +#include <iostream> +#include <complex> + +namespace math { + template<typename T> + struct vec3 { + T x; + T y; + T z; + }; +} + +template<typename T> +math::vec3<T> operator+(const math::vec3<T>& a, const math::vec3<T>& b) { + math::vec3<T> res; + + res.x = a.x + b.x; + res.y = a.y + b.y; + res.z = a.z + b.z; + + return res; +} + +template<typename T> +math::vec3<T> operator*(const T& scalar, const math::vec3<T>& vec) { + math::vec3<T> res; + + res.x = scalar * vec.x; + res.y = scalar * vec.y; + res.z = scalar * vec.z; + + return res; +} + +template<typename T> +math::vec3<T> operator-(const math::vec3<T>& a, const math::vec3<T>& b) { + return a + static_cast<T>(-1) * b; +} + +template<typename T> +std::ostream& operator<<(std::ostream& os, const math::vec3<T>& vec) { + os << "<" << vec.x << ", " + << vec.y << ", " + << vec.z << ">"; + + return os; +} + +int main(int argc, char *argv[]) { + + // using numeric_type = std::complex<int>; + using numeric_type = int; + + math::vec3<numeric_type> a = {1, 2, 3}; + math::vec3<numeric_type> b = {1, 2, 3}; + + std::cout << a + b << std::endl; + std::cout << a - b << std::endl; + std::cout << static_cast<numeric_type>(2) * b << std::endl; + + return 0; +} |