可能重复:
非成员运算符重载应放在何处?
在浏览SO时,我经常会发现涉及重载/定义a std::ostream& operator<<(std::ostream& os, const Foo& foo)或a的问题或答案Foo operator+(const Foo& l, const Foo& r).
虽然我知道如何以及何时(不)编写这些操作符,但我对namespace此事感到困惑.
如果我有以下课程:
namespace bar
{
class Foo {};
}
Run Code Online (Sandbox Code Playgroud)
namespace我应该在哪个中编写不同的运算符定义?
// Should it be this
namespace bar
{
std::ostream& operator<<(std::ostream& os, const Foo& foo);
}
// Or this ?
namespace std
{
ostream& operator<<(ostream& os, const bar::Foo& foo);
}
// Or this ?
std::ostream& operator<<(std::ostream& os, const bar::Foo& foo);
Run Code Online (Sandbox Code Playgroud)
同样的问题适用于operator+.那么,这里的好习惯是什么?为什么?
我在/sf/answers/3636592081/中询问了以下内容 :
我想超载
template<class T> ostream& operator<<(ostream& os, const optional<unique_ptr<T>>&).
在评论中,@ Yakk - Adam Nevraumont指出:
这个问题的答案是"你做不到".对于通用类型T,没有合法的方法可以做到这一点; 我可以解释原因,但这样做会有新的问题/答案
我正在创造一个新的Q.以接受这种报价......