c++ - 跨命名空间覆盖运算符

标签 c++ templates namespaces operator-overloading argument-dependent-lookup

这个问题是关于 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/

相关文章:

c++ - ORM 事务提交上的 Wt Segfault

c++ - std::vector.pop_back() 会改变 vector 的容量吗?

c++ - 将数字隐式转换为整型常量

c++ - 经典的 C++ 静态初始化顺序惨败重温

c++ - 乘法类型的确定

php - 在层次结构目录结构中使用 PHP 命名空间错误

object - 命令行参数 - 需要对象 : 'objshell.NameSpace(...)'

c++ - 连接qt和matlab时出错

c++ - 在类中声明一个枚举

c++ - 如何在 5 秒后关闭窗口?