Is it allowed to overload operators, such as operator+
for a combination of a standard library type and a built-in type, when such an overload doesn't exist?
For example, is it legal to implement the following operator in the default namespace or a user-defined namespace:
std::string operator+(const std::string& s, int right) { ... }
I know there are various restrictions about implementing things in the std::
namespace, but it isn't clear to me if there is any rule against the above (whether it's a good idea is of course an entirely different matter!).
For example, is it legal to implement the following operator in the default namespace or a user-defined namespace:
std::string operator+(const std::string& s, int right) { ... }
Yes, it's perfectly legal to do this. The only restrictions are about adding names to namespace std
or specializing member function function templates or class templates or adding deduction guides for class templates in std
.
There's nothing that stops you from writing something like:
namespace N {
std::string operator+(std::string s, int ) { return s; }
}
That is a well-formed program, per the standard. However note that since by definition your operators will not have any program-defined types in them, they will never be found by ADL. Since they are operators, which typically are found by ADL, this in of itself may be a reason to avoid such a pattern:
namespace U {
auto foo() {
return "hello"s + 1; // error: name lookup doesn't find our operator
}
auto bar() {
using namespace N;
return "hello"s + 1; // ok: for some definition of ok
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With