【发布时间】:2015-11-26 09:22:01
【问题描述】:
我对@987654323@ 的两个定义之间的冲突感到困扰。
假设我一直是 ACE 库的忠实粉丝,并且一直在我的代码中使用 ACE_Time_Value。有一天,我注意到 ACE 6.x 已经发布,并试图将我的代码从 ACE 5.x 迁移到 6.x。然后我遇到了一个问题:ACE 6.x 在全局命名空间中新引入了operator<<(std::ostream &, const ACE_Time_Value &),但是我的代码从5.x 时代就实现了我自己版本的operator<<,两个operator<< 冲突了。不幸的是,“官方”operator<< 的输出并不令人满意,我需要继续使用我自己的版本。我怎么能假装在全局命名空间中没有“官方”operator<<?幸运的是(?)我所有的代码都在我自己的命名空间下。
从概念上讲,我的问题可以概括为:
#include <iostream>
using namespace std;
struct ACE_Time_Value { };
ostream &operator<<(ostream &os, const ACE_Time_Value &) { os << "Apple" ; }
void foo(const ACE_Time_Value &) { cout << "Cherry" << endl; }
namespace mine {
ostream &operator<<(ostream &os, const ACE_Time_Value &) { os << "Banana" ; }
void foo(const ACE_Time_Value &) { cout << "Durian" << endl; }
void bar() {
ACE_Time_Value t;
::mine::foo(t); // OK
// cout << "The current time is " <<
// t << endl; // error: ambiguous overload for 'operator<<'
}
}
int main() {
mine::bar();
}
【问题讨论】:
-
这是一个可怕的问题,我找不到任何好的解决方案。一些丑陋的变通方法可能是将
ostreams 包装到一个helper 类My_ostream中,并提供一个operator<<,它与std::ostream的所有类型的版本相同,但ACE_Time_Value除外,然后使用那些包装的流而不是标准的。 -
从供应商标题中注释掉错误的
operator<<可能是最好的解决方案
标签: c++ namespaces operator-overloading shadowing