Re: [問題] C++ namespace 解析問題

作者: nevak (^o^)   2020-02-17 02:28:33
假設我理解正確的話,你原本的code大概像這樣
https://godbolt.org/z/-VzRbV
而namespace是不可改動的Library code
這個前提下你想要特化std::array<int, 10> ostream << operator
剛剛試了一下有三種做法:
1. 就像你說的,使用
namespace Hello { using ::operator<<; }
https://godbolt.org/z/EhZtjz
2. 繼承或是包裝std::array,並且實作新class的operator<<
https://godbolt.org/z/n-8UAX
3. 在namespace std裡實作array operator<<
https://godbolt.org/z/co32fi
※ 引述 《johnjohnlin》 之銘言:
: 標題: [問題] C++ namespace 解析問題
: 時間: Sun Feb 16 17:22:25 2020
:  
: 開發平台(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) 嗎?
: 」
:  
:
作者: johnjohnlin (嗯?)   2020-02-17 20:21:00
為什麼3能編譯?規則不會解析global但是會解析std?
作者: nevak (^o^)   2020-02-17 21:06:00
http://bit.ly/326nNnx Koenig lookup實際上規則並不會往parent namespace,找,但是會往argument type define 的namespace 找

Links booklink

Contact Us: admin [ a t ] ucptt.com