【发布时间】:2017-03-19 06:36:08
【问题描述】:
我有一个命名空间my_space 并将函数模板定义为
namespace my_space
{
template<class T>
ostream operator<<(ostream& os, T const& t)
{ ... }
}
我希望这个函数只适用于我在my_space 中的类,或者它可能对不在my_space 中的某些类型变得模棱两可。例如
namespace my_space
{
void f()
{
cout << "test"; //overload ambiguous
}
}
有什么办法可以避免吗?
【问题讨论】:
-
对于不在
my_space中的类型,如果你写other_type ot; std::cout << ot;之类的东西,你的函数将不会被使用。够了吗? -
查看示例
-
简短的回答是不要在你的命名空间中重载这样的运算符。照原样,您的代码会导致歧义,因为它依赖于
using namespace std的生效。完全消除这种依赖(即在您的命名空间中将ostream完全指定为std::ostream)。此外,与std::ostream一起使用的operator<<()函数返回一个引用 - 按值返回保证您的代码不会编译。 -
这里打错,在原代码中使用std::。
-
@user1899020 我还是听不懂你的问题;这是模棱两可的。 rextester.com/JRGB3285
标签: c++ c++11 templates namespaces