summaryrefslogtreecommitdiffstats
path: root/operator-overloading.cpp
blob: 92ef2d87fd4a676fc252682a6e6c84b8f26d94a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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;
}