From 54cc9c7e0a0c7fb95e5b5ecafc86a06f6cbe40db Mon Sep 17 00:00:00 2001 From: Nao Pross Date: Sat, 8 Dec 2018 14:20:30 +0100 Subject: Add overly complicated templated operator overloading example --- operator-overloading.cpp | 62 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 operator-overloading.cpp 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 +#include + +namespace math { + template + struct vec3 { + T x; + T y; + T z; + }; +} + +template +math::vec3 operator+(const math::vec3& a, const math::vec3& b) { + math::vec3 res; + + res.x = a.x + b.x; + res.y = a.y + b.y; + res.z = a.z + b.z; + + return res; +} + +template +math::vec3 operator*(const T& scalar, const math::vec3& vec) { + math::vec3 res; + + res.x = scalar * vec.x; + res.y = scalar * vec.y; + res.z = scalar * vec.z; + + return res; +} + +template +math::vec3 operator-(const math::vec3& a, const math::vec3& b) { + return a + static_cast(-1) * b; +} + +template +std::ostream& operator<<(std::ostream& os, const math::vec3& vec) { + os << "<" << vec.x << ", " + << vec.y << ", " + << vec.z << ">"; + + return os; +} + +int main(int argc, char *argv[]) { + + // using numeric_type = std::complex; + using numeric_type = int; + + math::vec3 a = {1, 2, 3}; + math::vec3 b = {1, 2, 3}; + + std::cout << a + b << std::endl; + std::cout << a - b << std::endl; + std::cout << static_cast(2) * b << std::endl; + + return 0; +} -- cgit v1.2.1