Wenzel Jakob | 38bd711 | 2015-07-05 20:05:44 +0200 | [diff] [blame] | 1 | /* |
Wenzel Jakob | a576e6a | 2015-07-29 17:51:54 +0200 | [diff] [blame] | 2 | example/example3.cpp -- operator overloading |
Wenzel Jakob | 38bd711 | 2015-07-05 20:05:44 +0200 | [diff] [blame] | 3 | |
| 4 | Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch> |
| 5 | |
| 6 | All rights reserved. Use of this source code is governed by a |
| 7 | BSD-style license that can be found in the LICENSE file. |
| 8 | */ |
| 9 | |
| 10 | #include "example.h" |
| 11 | #include <pybind/operators.h> |
| 12 | |
| 13 | class Vector2 { |
| 14 | public: |
| 15 | Vector2(float x, float y) : x(x), y(y) { std::cout << "Value constructor" << std::endl; } |
| 16 | Vector2(const Vector2 &v) : x(v.x), y(v.y) { std::cout << "Copy constructor" << std::endl; } |
| 17 | Vector2(Vector2 &&v) : x(v.x), y(v.y) { std::cout << "Move constructor" << std::endl; v.x = v.y = 0; } |
| 18 | ~Vector2() { std::cout << "Destructor." << std::endl; } |
| 19 | |
| 20 | std::string toString() const { |
| 21 | return "[" + std::to_string(x) + ", " + std::to_string(y) + "]"; |
| 22 | } |
| 23 | |
| 24 | void operator=(const Vector2 &v) { |
| 25 | cout << "Assignment operator" << endl; |
| 26 | x = v.x; |
| 27 | y = v.y; |
| 28 | } |
| 29 | |
| 30 | void operator=(Vector2 &&v) { |
| 31 | cout << "Move assignment operator" << endl; |
| 32 | x = v.x; y = v.y; v.x = v.y = 0; |
| 33 | } |
| 34 | |
| 35 | Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); } |
| 36 | Vector2 operator-(const Vector2 &v) const { return Vector2(x - v.x, y - v.y); } |
| 37 | Vector2 operator-(float value) const { return Vector2(x - value, y - value); } |
| 38 | Vector2 operator+(float value) const { return Vector2(x + value, y + value); } |
| 39 | Vector2 operator*(float value) const { return Vector2(x * value, y * value); } |
| 40 | Vector2 operator/(float value) const { return Vector2(x / value, y / value); } |
| 41 | Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; } |
| 42 | Vector2& operator-=(const Vector2 &v) { x -= v.x; y -= v.y; return *this; } |
| 43 | Vector2& operator*=(float v) { x *= v; y *= v; return *this; } |
| 44 | Vector2& operator/=(float v) { x /= v; y /= v; return *this; } |
| 45 | private: |
| 46 | float x, y; |
| 47 | }; |
| 48 | |
| 49 | void init_ex3(py::module &m) { |
| 50 | py::class_<Vector2>(m, "Vector2") |
| 51 | .def(py::init<float, float>()) |
| 52 | .def(py::self + py::self) |
| 53 | .def(py::self + float()) |
| 54 | .def(py::self - py::self) |
| 55 | .def(py::self - float()) |
| 56 | .def(py::self * float()) |
| 57 | .def(py::self / float()) |
| 58 | .def(py::self += py::self) |
| 59 | .def(py::self -= py::self) |
| 60 | .def(py::self *= float()) |
| 61 | .def(py::self /= float()) |
| 62 | .def("__str__", &Vector2::toString); |
| 63 | |
| 64 | m.attr("Vector") = m.attr("Vector2"); |
| 65 | } |