[問題] template class 內 static 初始問題

看板C_and_CPP (C/C++)作者 (JOMI)時間7年前 (2018/06/22 17:03), 7年前編輯推噓3(3018)
留言21則, 4人參與, 7年前最新討論串1/2 (看更多)
https://wandbox.org/permlink/skxmougiYnaw1f1a 一開始遭遇到這個compile warning warning: instantiation of variable 'Foo<int>::bar' required here, but no defin ition is available [-Wundefined-var-template] 其實我不太知道他為什麼會warning 我確實有define在test.cpp這個translation unit 不懂的是 他感覺找不到定義 卻讓我pass, run time 也有拿到對的數值. 而g++不會有warning 1. 到這邊我還是不知道到底哪裡寫的不夠正確? 然而我試著解決這warning 於是我把 上面的 //b. // extern template class Foo<int>; 打開 https://wandbox.org/permlink/j2ANWRBoeIZZJAHE link error undefined reference to `Foo<int>::Test()' 如果不呼叫 這個warning確實可以這樣解決 但我必須呼叫這function 2. 為什麼他這樣會說undefined? .h裡面明確有包含定義阿? 然而 //a. // template class Foo<int>; 打開後 3. 我認為我已經明確讓他產生程式碼了.... warning還是存在 回歸1. 的問題 我到底少做了什麼讓clang這樣出warning 4. 對於template class內 有static function or data 最正確的寫法該怎麼寫. 網路上有查到 在test.h 直接寫 template<class T> int Foo<T>::bar = 初始直; test.cpp一樣寫 template<> int Foo<int>::bar = 123; 但我實際上在專案遇到一個況狀是 我某個cpp 寫Foo<int>::bar 拿到的卻是.h給的初始直(我認為是他初始化順序優先於te st.cpp) 所以目前毫無辦法處理這warning 5. 這似乎沒辦法用static是internal linkage 來解釋...讓我整個無法通透理解 請教各位有什麼方法處理這問題 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.242.196.52 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1529658222.A.8D0.html

06/22 18:21, 7年前 , 1F
你對bar做模板特化 並不會幫你生整個class
06/22 18:21, 1F

06/22 18:23, 7年前 , 2F
所以test.cpp要補Test()的特化; 你的extern才抓的到
06/22 18:23, 2F

06/22 18:24, 7年前 , 3F
3跟4我不確定 感覺是undefined behavior 要查一下XD
06/22 18:24, 3F
※ 編輯: lovejomi (27.242.196.52), 06/22/2018 18:27:10

06/23 00:19, 7年前 , 4F

06/23 00:19, 7年前 , 5F
你是要這樣嗎
06/23 00:19, 5F

06/23 02:02, 7年前 , 6F

06/23 02:02, 7年前 , 7F
是不是這樣寫最正確?這樣感覺這static變數變成external
06/23 02:02, 7F

06/23 02:02, 7年前 , 8F
linkage了?
06/23 02:02, 8F

06/23 02:07, 7年前 , 9F
static member本來就是external linkage吧
06/23 02:07, 9F

06/23 02:08, 7年前 , 10F
static variable和static member是不一樣的
06/23 02:08, 10F

06/23 02:08, 7年前 , 11F
(雖然他們都叫static..)
06/23 02:08, 11F

06/23 14:48, 7年前 , 12F
謝謝,只是這個warning 我在編譯出binary後如果沒改程
06/23 14:48, 12F

06/23 14:48, 7年前 , 13F
式碼再編一次就沒有warning了,為什麼呢
06/23 14:48, 13F

06/23 23:08, 7年前 , 14F
因為沒有真的compile到? (亂猜的XD)
06/23 23:08, 14F

06/24 16:03, 7年前 , 15F
incremental building 你re-compile或cleanup就有了
06/24 16:03, 15F

06/24 22:50, 7年前 , 16F
但這warning到底會不會對程式本身有可能有錯誤的風險呀
06/24 22:50, 16F

06/24 22:50, 7年前 , 17F
?不理他感覺也沒怎樣
06/24 22:50, 17F

06/25 10:59, 7年前 , 18F
他無法判斷會不會 比方說有個warning是
06/25 10:59, 18F

06/25 10:59, 7年前 , 19F
not all control paths return a value 這個就是會讓你
06/25 10:59, 19F

06/25 10:59, 7年前 , 20F
過 但是你是有可能有runtime issuey
06/25 10:59, 20F

06/25 11:00, 7年前 , 21F
但是有些則是完全是murmur 這要自己判斷一下
06/25 11:00, 21F
文章代碼(AID): #1RBBjkZG (C_and_CPP)
文章代碼(AID): #1RBBjkZG (C_and_CPP)