[問題] 使用template function的時候去判定型別

看板C_and_CPP (C/C++)作者 (raison detre)時間13年前 (2013/05/08 12:18), 編輯推噓3(302)
留言5則, 4人參與, 最新討論串1/1
以下是我的程式碼 我希望可以在使用 template function 的時候自動去判定型別 尋找適合的function來用 當我呼叫push時 如果值是 int 或是std::string都可對應到正確的function 可是如果是 繼承 IF 的物件卻還是會跑到 template <typename T> void Push(T val) 裏頭 請問還有其他作法嗎 class IF { public: virtual std::string ToString()=0; }; class Array : public IF { private: std::vector<std::string> m_arr; public: Array(){} ~Array(){} template <typename T> void Push(T val) { std::stringstream _ss; _ss << val; m_arr.push_back(_ss.str()); } void Push(const std::string& val) { m_arr.push_back("\"" + val + "\""); } void Push(IF& obj) { m_arr.push_back( obj.ToString() ); } virtual std::string ToString() { // to do } }; -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.220.71.34

05/08 12:27, , 1F
你根本不需要template吧...function overloading就好了
05/08 12:27, 1F

05/08 12:31, , 2F
喔 看錯了....orz
05/08 12:31, 2F

05/08 13:45, , 4F
好的,謝謝你,我研究一下^^
05/08 13:45, 4F

05/12 21:57, , 5F
是不是傳參不對?要不要把你call的方法也寫出來
05/12 21:57, 5F
文章代碼(AID): #1HYT8SC8 (C_and_CPP)
文章代碼(AID): #1HYT8SC8 (C_and_CPP)