这个问题是关于 C++03 的。
在我的命名空间中,我对来自不同命名空间的类进行类型定义,然后尝试为该类重载运算符。我知道 typedef 只是一个别名而不是一个新类型,因此当 ADL 启动时我的重载没有被使用。起初这对我来说并不直观。我想知道是否有办法“选择”我的重载,或者以某种方式“引导”ADL 到正确的命名空间?
下面是一个简化的案例:
#include <iostream>
namespace boost
{
template<typename T>
struct some_type{};
template<typename T, typename U>
T& operator<<(T& os, some_type<U> const& obj)
{
os << "Boost implementation";
return os;
}
}
namespace my
{
typedef boost::some_type<int> typedefed_type;
template<typename T>
T& operator<<(T& os, typedefed_type const& obj)
{
os << "My implementation";
return os;
}
}
namespace other
{
template<typename T>
void f(T const& obj)
{
// using namespace my; // ***
std::cout << obj << std::endl;
}
}
int main(int argc, char* argv[])
{
my::typedefed_type obj;
other::f(obj);
return 0;
}
在这里,我使用来自 ::my
的对象调用 other::f()
,尽管 obj
实际上是一个 typedef boost
中的一个类。这输出:Boost 实现
。我可以做些什么来运行 My implementation
?标记为 //***
的行似乎可以做到这一点,但我不想让 other::f()
关心模板参数来自哪些命名空间。
最佳答案
您可以劫持 boost
中的通用实现通过在您自己的文件中重载使用相同命名空间的函数来命名空间。
继续在 my
中拥有您自己的通用实现命名空间然后添加:
namespace boost
{
typedef some_type<int> typedefed_type;
template<typename T>
T& operator<<(T& os, typedefed_type const& obj)
{
return my::operator<<(os, obj);
}
}
然后,您对 <<
的使用运算符可以很简单 other
命名空间。
namespace other
{
template<typename T>
void f(T const& obj)
{
std::cout << obj << std::endl;
}
}
关于c++ - 跨命名空间覆盖运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35514781/