跨名称空间重载函数一定很困难吗?

Does it have to be hard to overload functions across namespaces?

本文关键字:空间 重载 函数      更新时间:2023-10-16

我一直在写一些代码,基本上是这样的结构

namespace util {
    void read (int &);
    template <typename T>
    void read (T &);
}
void foo ();
using namespace util;
namespace { // A
    void read (MyType &, int);
    void do_something () {
        MyType t;
        int i;
        // using util::read; // B
        read (i); // C
        read (t,i); // D
    }
}
void foo () {
    do_something ();
}

第一行C没有编译,除非我完全限定它为util::read(i)或未注释的行B,但这使得D行失败。

特化模板util::read是不可能的,因为参数的数量不同(直到c++ 0x)。

将行A转换为namespace util不是一个选项,因为我不想导出新的read

我可以重命名read(MyType&,int),但这会破坏ahem样式。

是否有一种方法可以使这些跨命名空间的重载工作得很好?他们不应该这么做有什么好理由吗?

是的,很难。事实上这是不可能的。

你能做的最好的就是隐藏名字。您使用using (B)来解决名称隐藏带来的复杂性是正确的,当您还重载函数时—D在这种情况下仍然有效。

不同的命名空间意味着包含在其中的标识符的不同全名,因此它们不会相互重载(至少对于微软的编译器和GCC来说是这样的-我不确定标准如何定义)。

试试这个:

namespace util {
    void read (int &);
    template <typename T>
    void read (T &);
}
void foo ();
namespace { // A
    using ::util::read;
    void read (MyType &, int);
    void do_something () {
        MyType t;
        int i;
        // using util::read; // B
        read (i); // C
        read (t,i); // D
    }
}
void foo () {
    do_something ();
}