Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed to overload operator+ for a standard library type and a built-in type?

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!).

like image 805
BeeOnRope Avatar asked Jan 29 '23 04:01

BeeOnRope


1 Answers

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
    }
}
like image 100
Barry Avatar answered Apr 29 '23 04:04

Barry