[问题] C++ namespace 解析问题

楼主: johnjohnlin (嗯?)   2020-02-16 17:22:25
开发平台(Platform): (Ex: Win10, Linux, ...)
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
ArchLinux gcc 9.2
但是这个应该不重要
问题(Question):
顺便在 Stackoverflow 问了
https://stackoverflow.com/questions/60246803
假设我使用到了一个叫做 Hello 的 library 在 hello.h 下
里面有一个 template function 用到了 cout
namespace Hello {
template<class T>
void World(std::ostream& os, const T& t) { os << t; }
}
我本来认为只要定义好对应的 operator,这个程式就能编译
所以我传一个 World(std::cout, std::array<int,10>{}) 进去
但是出现 compile error 说找不到 operator
Google 了一下应该是这个问题
https://stackoverflow.com/questions/60246803/
简单的说 operator<< 是一个“名字”
所以被 Hello 下面的 operator<< 覆蓋掉了所有外层的 operator<<
(实际上 Hello 是一个蛮大的 library,所以里面应该是有 overload 到)
把问题简化如下
void f(int) {}
void f(int,int) {}
namespace Hello {
using ::f;
void f(int,int,int) {}
void World()
{
f(100);
f(100, 200);
f(100, 200, 300);
}
};
int main()
{
Hello::World();
return 0;
}
这个程式没有 using ::f; 就不能编译
现在问题来了:

因为 World 是在 library 下面,所以我不能改说让他去 call ::f(100);
所以唯一的方法是在我的 code 其他地方加上 namespace { using ::f; }
但是这样感觉就会拉一票东西进去 Hello 里面
不知道会不会干扰到原本的 library
我希望,例如说这个范例中,可以只 import ::f(int) 吗?

Links booklink

Contact Us: admin [ a t ] ucptt.com