Deleted Added
sdiff udiff text old ( 11986:c12e4625ab56 ) new ( 12391:ceeca8b41e4b )
full compact
1/*
2 tests/test_operator_overloading.cpp -- operator overloading
3
4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.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 "pybind11_tests.h"
11#include "constructor_stats.h"
12#include <pybind11/operators.h>
13
14class Vector2 {
15public:
16 Vector2(float x, float y) : x(x), y(y) { print_created(this, toString()); }
17 Vector2(const Vector2 &v) : x(v.x), y(v.y) { print_copy_created(this); }
18 Vector2(Vector2 &&v) : x(v.x), y(v.y) { print_move_created(this); v.x = v.y = 0; }
19 ~Vector2() { print_destroyed(this); }
20
21 std::string toString() const {
22 return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
23 }
24
25 void operator=(const Vector2 &v) {
26 print_copy_assigned(this);
27 x = v.x;
28 y = v.y;
29 }
30
31 void operator=(Vector2 &&v) {
32 print_move_assigned(this);
33 x = v.x; y = v.y; v.x = v.y = 0;
34 }
35
36 Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
37 Vector2 operator-(const Vector2 &v) const { return Vector2(x - v.x, y - v.y); }
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/(float value) const { return Vector2(x / value, y / value); }
42 Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
43 Vector2& operator-=(const Vector2 &v) { x -= v.x; y -= v.y; return *this; }
44 Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
45 Vector2& operator/=(float v) { x /= v; y /= v; return *this; }
46
47 friend Vector2 operator+(float f, const Vector2 &v) { return Vector2(f + v.x, f + v.y); }
48 friend Vector2 operator-(float f, const Vector2 &v) { return Vector2(f - v.x, f - v.y); }
49 friend Vector2 operator*(float f, const Vector2 &v) { return Vector2(f * v.x, f * v.y); }
50 friend Vector2 operator/(float f, const Vector2 &v) { return Vector2(f / v.x, f / v.y); }
51private:
52 float x, y;
53};
54
55test_initializer operator_overloading([](py::module &m) {
56 py::class_<Vector2>(m, "Vector2")
57 .def(py::init<float, float>())
58 .def(py::self + py::self)
59 .def(py::self + float())
60 .def(py::self - py::self)
61 .def(py::self - float())
62 .def(py::self * float())
63 .def(py::self / float())
64 .def(py::self += py::self)
65 .def(py::self -= py::self)
66 .def(py::self *= float())
67 .def(py::self /= float())
68 .def(float() + py::self)
69 .def(float() - py::self)
70 .def(float() * py::self)
71 .def(float() / py::self)
72 .def("__str__", &Vector2::toString)
73 ;
74
75 m.attr("Vector") = m.attr("Vector2");
76});