Re: [語法] template 用法

看板C_and_CPP (C/C++)作者 (我要加入劍道社!)時間16年前 (2009/09/30 10:18), 編輯推噓1(102)
留言3則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《POSIX (tedium of chores)》之銘言: : 測試用的template class, : 限制他的template parameter 只能用s_limit 這個structure(當成namespace用) : template <typename TTT = s_limit > : class test_limit : :public dummy<typename TTT::iii, typename TTT::fff > : { : public: : test_limit(){cout<<"constructor"<<endl;} : ~test_limit(){cout<<"destructor"<<endl;} : }; 這個東西,叫作 default argument 也就是當你寫 test_limit<> 的時候 compiler 會幫你把 s_limit 代進去變成 test_limit<s_limit> : 所以main 裡面宣告只能這樣用 : int main(){ : test_limit<s_limit> foo; : return 0; : } : 新版的c++ standard 有針對template argument 做更多的保護 : 但目前似乎以這種方式可以達到"自訂的保護" 如果你想限制只有某些 type 才能當作 template parameter 常見的方法是 specialization template <typename T> class test_limit; // 只宣告,不定義 template <> class test_limit<s_limit> { // test_limit members }; 這麼一來,使用者如果用 s_limit 以外的型別代入 test_limit 中, 會產生 compile error。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.29.108

09/30 12:27, , 1F
同意 之所以用dummy class是因為原code內有繼承的關係在
09/30 12:27, 1F

09/30 12:27, , 2F
所以才簡化成dummy template class
09/30 12:27, 2F

09/30 12:29, , 3F
原po的方法也不錯 !!! 推
09/30 12:29, 3F
文章代碼(AID): #1Amh_Wn3 (C_and_CPP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
2
6
完整討論串 (本文為第 2 之 2 篇):
2
6
文章代碼(AID): #1Amh_Wn3 (C_and_CPP)