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

看板C_and_CPP (C/C++)作者 (^o^)時間5年前 (2020/02/17 02:28), 編輯推噓1(103)
留言4則, 2人參與, 5年前最新討論串2/2 (看更多)
假設我理解正確的話,你原本的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) 嗎? : 」 :   : -- : ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.175.53 (臺灣) : ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1581844949.A.A0C.html -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.231.46.83 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1581877718.A.4F7.html

02/17 20:21, 5年前 , 1F
為什麼3能編譯?規則不會解析global但是會解析std?
02/17 20:21, 1F

02/17 21:06, 5年前 , 2F
http://bit.ly/326nNnx Koenig lookup
02/17 21:06, 2F

02/17 21:07, 5年前 , 3F
實際上規則並不會往parent namespace,找,但是會往argume
02/17 21:07, 3F

02/17 21:07, 5年前 , 4F
nt type define 的namespace 找
02/17 21:07, 4F
文章代碼(AID): #1UIOdMJt (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1UIOdMJt (C_and_CPP)