[問題] 想請問一個enable_if 跟tempate的問題

看板C_and_CPP作者 (^^)時間10年前 (2015/11/03 13:24), 編輯推噓2(207)
留言9則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) c++11 問題(Question): 想請問一個如何把template的實作放在cpp檔, 並搭配enable_if~ 如果都放在header檔的話是可以正常運作 template<class K, class V> class aaa{ template< class T = K, typename std::enable_if<std::is_same<T, int>::value, int>::type = 0> RC test(K key){ cout << "this is int:" << key << endl; }; }; http://codepad.org/RYllQky3 不過如果把implement放在cpp檔 如下: //aaa.hpp template<class K, class V> class aaa{ template< class T = K, typename std::enable_if<std::is_same<T, int>::value, int>::type = 0> RC test(K key); }; //aaa.cpp template< class T = K, typename std::enable_if<std::is_same<T, int>::value, int>::type = 0> RC aaa<K, V>::test(K key){ cout << "this is int:" << key << endl; }; 就會出現下面的錯誤 error: ‘K’ was not declared in this scope 想請問各位前輩有遇過類似的錯誤嗎 試過了多寫法都有錯, 這只是其中一種寫法~ 麻煩可以幫我解答 另外可已請問一下 如果想要將template實作放在CPP, 除了一次include hpp+cpp兩個檔之外 還有其他的方法嗎 非常謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.230.218.152 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1446528266.A.E3F.html

11/03 15:11, , 1F
template印象中只能放在header裡面
11/03 15:11, 1F

11/03 15:11, , 2F
compile unit不同 無法幫你產生
11/03 15:11, 2F

11/03 20:11, , 3F
1.你的K,V不見了 2.定義時不能寫template參數預設值
11/03 20:11, 3F

11/04 09:17, , 4F
借問,這種實作分離的template用意為何? 也只能實作的
11/04 09:17, 4F

11/04 09:17, , 5F
那個cpp使用 那幹嘛寫在.h讓人看到呢?
11/04 09:17, 5F

11/04 11:48, , 6F
define時,template default parameter不用寫出,例如cl
11/04 11:48, 6F

11/04 11:48, , 7F
ass T = K的= K
11/04 11:48, 7F

11/04 19:58, , 8F
非常謝謝各位的回答^^
11/04 19:58, 8F

11/04 20:00, , 9F
想分離主要是因為template的成員太多了~
11/04 20:00, 9F
文章代碼(AID): #1ME4KAu_ (C_and_CPP)