05 Operators
Operators
Operators can be customized for custom types. This is called operator overloading.
Operators with two or more arguments should be overloaded as non-member functions (or friend functions).
This prevents the left operand from being converted to a different type and therefore protects from unwanted asymmetries.
See What are the Basic Rules and Idioms for Operator Overloading?
class Distance {
long double m_meters;
public:
explicit Distance(long double meters) : m_meters(meters) {}
Distance& operator+=(const Distance& rhs) {
m_meters += rhs.m_meters;
return *this;
}
friend Distance operator+(const Distance& lhs, const Distance& rhs) {
Distance result = lhs;
result += rhs;
return result;
}
Distance& operator-=(const Distance& rhs) {
m_meters -= rhs.m_meters;
return *this;
}
friend Distance operator-(const Distance& lhs, const Distance& rhs) {
Distance result = lhs;
result -= rhs;
return result;
}
}
Literals
Literals are used to represent values in source code. They are used to initialize variables and constants.
User-defined Literals
User-defined literals can be used to create custom literals.
They are defined by overloading the ""_literal operator.
Literal operators must be defined in a namespace or global scope.
constexpr Distance operator""_m(long double meters) {
return Distance(meters);
}
constexpr Distance operator""_km(long double kilometers) {
return Distance(kilometers * 1000);
}
constexpr Distance operator""_mi(long double miles) {
return Distance(miles * 1609.344);
}
Overloading
Methods with the same name can be overloaded. The compiler will then choose the correct method based on the signature and current scope.
Signature
The method signature consists of:
- method name
- argument…
- types
- number
- value cateogry
- namespace
- class
Ambiguity
If the compiler cannot decide which method to use, it will throw an error. This is called ambiguity.
Ambiguity can be caused by:
- multiple methods with the same signature
- import of multiple namespaces with members of the same name
- inheritance
In short: Problems with ambiguity means that there are multiple methods with the same signature.