Re: [語法] template 用法
看板C_and_CPP (C/C++)作者littleshan (我要加入劍道社!)時間16年前 (2009/09/30 10:18)推噓1(1推 0噓 2→)留言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
09/30 12:27, 1F
→
09/30 12:27, , 2F
09/30 12:27, 2F
→
09/30 12:29, , 3F
09/30 12:29, 3F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章