Operators
Operator()
The function call operator allows objects to be called like functions in Python.
// operator() wrapping
#include <c2py/c2py.hpp>
namespace mylib {
class multiplier {
int factor_;
public:
multiplier(int factor) : factor_(factor) {}
// Function call operator
int operator()(int value) const { return factor_ * value; }
};
} // namespace mylib
The Python usage:
from mymodule import Multiplier
mult = Multiplier(5)
result = mult(10) # Calls operator()
print(result) # 50
Operator[]
The subscript operator enables indexing and item access in Python.
// operator[] wrapping
#include <c2py/c2py.hpp>
#include <vector>
namespace mylib {
class container {
std::vector<int> data_;
public:
container(size_t size) : data_(size, 0) {}
// Subscript operator for reading
int operator[](size_t index) const { return data_[index]; }
// Subscript operator for writing
int &operator[](size_t index) { return data_[index]; }
size_t size() const { return data_.size(); }
};
} // namespace mylib
The Python usage:
from mymodule import Container
c = Container(10)
c[0] = 42
print(c[0]) # 42
Arithmetic Operators
Arithmetic operators (+, -, *, /, etc.) are automatically wrapped.
// Arithmetic operators
#include <c2py/c2py.hpp>
namespace mylib {
class vector {
public:
double x, y;
vector(double x, double y) : x(x), y(y) {}
// Arithmetic operators
vector operator+(vector const &other) const { return vector(x + other.x, y + other.y); }
vector operator-(vector const &other) const { return vector(x - other.x, y - other.y); }
vector operator*(double scalar) const { return vector(x * scalar, y * scalar); }
vector &operator+=(vector const &other) {
x += other.x;
y += other.y;
return *this;
}
};
} // namespace mylib
The Python usage:
from mymodule import Vector
v1 = Vector(1.0, 2.0)
v2 = Vector(3.0, 4.0)
v3 = v1 + v2
print(v3.x, v3.y) # 4.0, 6.0
Comparison Operators
Comparison operators (==, !=, <, >, <=, >=) are wrapped when defined.
// Comparison operators
#include <c2py/c2py.hpp>
#include <tuple>
namespace mylib {
class version {
int major_, minor_, patch_;
public:
version(int major, int minor, int patch) : major_(major), minor_(minor), patch_(patch) {}
// C++20 spaceship operator
auto operator<=>(version const &other) const { return std::tie(major_, minor_, patch_) <=> std::tie(other.major_, other.minor_, other.patch_); }
bool operator==(version const &other) const { return major_ == other.major_ && minor_ == other.minor_ && patch_ == other.patch_; }
};
} // namespace mylib
The Python usage:
from mymodule import Version
v1 = Version(1, 0, 0)
v2 = Version(2, 0, 0)
print(v1 < v2) # True
print(v1 == v2) # False