跨名称空间重载函数一定很困难吗?
Does it have to be hard to overload functions across namespaces?
我一直在写一些代码,基本上是这样的结构
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 ();
}
相关文章:
- 从父命名空间重载类型
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- Visual Studio 无法解决类和命名空间中重载的明确函数
- 在类设计中查找外部命名空间中的重载运算符
- 重载运算符 + 用于向量:命名空间标准
- 在命名空间中使用指令和函数重载
- 使用类指针重载C++命名空间函数模板专用化替代方法?
- 为什么找不到使用命名空间中定义的类型实例化的 std::weak_ptr 的重载运算符==?
- 在命名空间内的类中使用带有运算符重载的字符串流时"no match for ‘operator>>’"
- 在命名空间内的 lambda 中使用时未找到运算符重载
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- 为命名空间中的类重载运算符<<时发出警告
- 为在与类方法中的类相同的命名空间中定义的结构调用重载运算符
- 在全局命名空间中重载不依赖于用户定义类型的标准定义类型的运算符是否格式正确?
- 基于 SFINAE 的跨命名空间的运算符重载
- 将 boost odeint 与 std::map 和自定义向量空间代数一起使用时,没有可行的重载'='
- 如何在不同的命名空间中指定重载运算符
- 为什么使用范围解析运算符会更改调用全局命名空间中的哪个重载模板?
- 命名空间 + 重载 std::ostream <<运算符
- 跨名称空间重载函数一定很困难吗?