summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorNao Pross <naopross@thearcway.org>2018-12-08 14:20:30 +0100
committerNao Pross <naopross@thearcway.org>2018-12-08 14:20:30 +0100
commit54cc9c7e0a0c7fb95e5b5ecafc86a06f6cbe40db (patch)
treef9f295de06fdecc72a9f1a8dacfeff8ac47d80ec
parentAdd -Werror flag for compilation (diff)
downloadcplusplus-54cc9c7e0a0c7fb95e5b5ecafc86a06f6cbe40db.tar.gz
cplusplus-54cc9c7e0a0c7fb95e5b5ecafc86a06f6cbe40db.zip
Add overly complicated templated operator overloading example
-rw-r--r--operator-overloading.cpp62
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;
+}