Bee*_*ope 6 c++ operator-overloading user-defined-types language-lawyer
当不存在这样的重载时,是否允许重载运算符,例如operator+标准库类型和内置类型的组合?
例如,在默认命名空间或用户定义的命名空间中实现以下运算符是否合法:
std::string operator+(const std::string& s, int right) { ... }
Run Code Online (Sandbox Code Playgroud)
我知道在命名空间中实现事物有各种限制std::,但我不清楚是否有任何规则违反上述规定(当然这是否是一个好主意是完全不同的事情!)。
例如,在默认命名空间或用户定义的命名空间中实现以下运算符是否合法:
Run Code Online (Sandbox Code Playgroud)std::string operator+(const std::string& s, int right) { ... }
是的,这样做是完全合法的。唯一的限制是向namespace std成员函数模板或类模板添加名称或专门化,或者为std.
没有什么可以阻止你写这样的东西:
namespace N {
std::string operator+(std::string s, int ) { return s; }
}
Run Code Online (Sandbox Code Playgroud)
根据标准,这是一个格式良好的程序。但请注意,由于根据定义,您的运算符中不会包含任何程序定义的类型,因此 ADL 永远不会找到它们。由于它们是运算符,通常由 ADL 找到,因此这本身可能就是避免这种模式的一个原因:
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1077 次 |
| 最近记录: |