[問題] template + vector

看板C_and_CPP (C/C++)作者 (su27)時間2年前 (2022/03/29 18:12), 2年前編輯推噓2(206)
留言8則, 5人參與, 2年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) win10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) qt 問題(Question): dll的函數 void fun_1(vector<uchar> &val) void fun_2(vector<char> &val) 我在qt寫一個函數 功能是 填寫不同的dataType 調用來自DLL不同的函數 template <class type> static void Select_fun(vector<type> vtp) { if (std::is_same<type, uchar>::value) { vector<uchar> &temp=vtp; //<<這邊報錯 fun_1(temp); } else if (std::is_same<type, char>::value) { fun_2(vtp); //<<這邊報錯 } } 錯誤訊息 //------------------------------------ error: invalid initialization of reference of type 'std::vector<unsigned char>&' from expression of type 'std::vector<int>' vector<uchar> &temp=vtp; ^~~~ //------------------------------------ 請問我該如何解決 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.228.53.160 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1648548768.A.2A6.html ※ 編輯: su27 (125.228.53.160 臺灣), 03/29/2022 18:16:52

03/29 18:19, 2年前 , 1F
模板不會幫你繞掉type checking,請把偏特化拿出來用
03/29 18:19, 1F

03/29 18:19, 2年前 , 2F
更正 全特化
03/29 18:19, 2F

03/29 19:18, 2年前 , 3F
樓下 Su22
03/29 19:18, 3F

03/29 19:44, 2年前 , 4F
c++17以後的話也可以用if constexpr
03/29 19:44, 4F

03/29 21:49, 2年前 , 5F
錯誤訊息裡面為何會有vector<int>?
03/29 21:49, 5F
因為我只列出幾個 ※ 編輯: su27 (125.228.53.160 臺灣), 03/30/2022 20:10:57

03/31 05:26, 2年前 , 6F
If branch 在runtime 才會跑所以template 還是instant
03/31 05:26, 6F

03/31 05:26, 2年前 , 7F
iate 那段code 了
03/31 05:26, 7F

03/31 05:26, 2年前 , 8F
你要conditionally compile 要用constexpr if
03/31 05:26, 8F
文章代碼(AID): #1YGjkWAc (C_and_CPP)
文章代碼(AID): #1YGjkWAc (C_and_CPP)