看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) win10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) vs2017 我寫了一個類別 如下 (問題一) 我想要做到 如何知道typeA 是int 或 double 甚至是 Point 之類的 PS:這段程式碼沒法執行 在這裡會報錯 if (typeA == int) 請問想要做到這樣的功能要怎麼實現 謝謝 template <class typeA> class Ho_Data { private: public: int type ; vector <typeA> Data; Ho_Data() { if (typeA == int) { this->type = 0; } else if (typeA == double) { this->type = 1; } } }; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.135.141.239 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1581669811.A.FED.html
fenzhang: std::is_same 02/14 17:14
sarafciel: https://ideone.com/CWSLHb 02/14 17:23
可以了 謝謝 ※ 編輯: su27 (220.135.141.239 臺灣), 02/14/2020 17:29:09
harryooooooo: C++17以後的話可以把樓上的if改成if constexpr 02/14 21:14
johnjohnlin: C++11 之前的話用 template 特例化 02/14 22:11
oToToT: 如果是double,int之類的話,可能也可以考慮看看 02/14 22:47
oToToT: is_floating_point 02/14 22:47
KanzakiHAria: template特化就好+1 阿就base on type的語法還去 02/15 13:06
KanzakiHAria: 用== 也太幽默了吧 02/15 13:06
LPH66: 不過 if constexpr 達成的效果跟直接特化是一樣的 02/15 13:56
LPH66: 用 if constexpr 的好處應該只有在除去這判斷之外的部分 02/15 13:56
LPH66: 只要寫一次吧; 如果沒有這種共同部份的話直接特化就足夠了 02/15 13:57