[問題] 如何消除泛型的警告

看板C_and_CPP作者 (s4300026)時間4年前 (2019/08/27 15:59), 4年前編輯推噓1(1014)
留言15則, 3人參與, 4年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) win7 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) vc2010 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 如題 餵入的資料(Input): T = Point, K = float T = PointF, K = double 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): warning C4244 將 float 轉 int 可能導致資料遺失 將 double 轉 float 可能導致資料遺失 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) template <typename T, typename K> void func(T a, K b, T &c) { c.X = a.X * b; } 補充說明(Supplement): 原本以為 decltype 可以幫上忙, 但似乎不能這樣寫... c.X = (decltype c.X) (a.X * b); 正確寫法 c.X = (decltype (c.X)) (a.X * b); 看到 warning 很煩躁... 我知道T, K不能亂丟型態進去 因此我想要把泛型做成 class private 然後 public 指定的T K 感謝大大撥冗觀看 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.73.148.184 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1566892743.A.BC7.html ※ 編輯: s4300026 (42.73.148.184 臺灣), 08/27/2019 16:02:41

08/27 16:41, 4年前 , 1F
你的T跟K為什麼一定要帶會降轉的case進去呢?
08/27 16:41, 1F

08/27 17:55, 4年前 , 2F
因為 T 一定是Point或 PointF。 K至少要是float。 話說
08/27 17:55, 2F

08/27 17:55, 4年前 , 3F
我還打算傳自創的 PointD呢!
08/27 17:55, 3F

08/27 17:57, 4年前 , 4F
T是點位,K是我的放大倍率
08/27 17:57, 4F

08/27 19:48, 4年前 , 5F
這跟泛型無關, 是降轉的問題
08/27 19:48, 5F

08/27 19:49, 4年前 , 6F
以 T.X 是 int, K 是 float 來說的話
08/27 19:49, 6F

08/27 19:49, 4年前 , 7F
a.X * b 是一個 int 乘 float, 照規則會得到 float
08/27 19:49, 7F

08/27 19:50, 4年前 , 8F
然後你要把一個 float 塞進 c.X 這個 int 裡就噴 C4244 了
08/27 19:50, 8F

08/27 19:51, 4年前 , 9F
這裡跟泛型沾到邊的地方只有因為泛型你不知道 T.X 的型態
08/27 19:51, 9F

08/27 19:51, 4年前 , 10F
那麼用 decltype 是對的, 但你忘了括號
08/27 19:51, 10F

08/27 19:52, 4年前 , 11F
decltype 要帶一對 () 裡面放式子才是對的語法:
08/27 19:52, 11F

08/27 19:53, 4年前 , 12F
※ 編輯: s4300026 (42.73.148.184 臺灣), 08/28/2019 08:00:08

08/28 08:07, 4年前 , 13F
你說的沒錯,這確實是降轉的問題,但關鍵就在於泛型使
08/28 08:07, 13F

08/28 08:07, 4年前 , 14F
我無法用已知型別強制轉型,以及我不了解 decltype 該
08/28 08:07, 14F

08/28 08:07, 4年前 , 15F
怎麼使用。
08/28 08:07, 15F
※ 編輯: s4300026 (42.73.148.184 臺灣), 08/28/2019 08:09:25
文章代碼(AID): #1TPEB7l7 (C_and_CPP)