模板 policy類的簡單使用

2021-07-26 08:01:11 字數 1588 閱讀 4688

一、需求引入

到目前為止,我們一直都將累計(accumulation)與求和(summation)混為一談。顯然我們其實可以設想其它種類的累計。例如我們可以求給定之實值序列的乘積;如果被操作的實值是字串,我們可以將它們串接起來;甚至「尋找序列中的最大值」也可被歸結為累計問題。在所有情況中,accum()惟一需要修改的就是  total  +=  *beg。這個操作可被稱為「累計運算」過程中的乙個  policy(策略)。因此所謂  policy   class  就是這樣的  class:提供乙個介面,從而得以在演算法中運用一或多個  policies。 

二、實現

template

class accumulationtraits; 

template<> 

class accumulationtraits 

}; template<> 

class accumulationtraits 

};  

template<> 

class accumulationtraits 

}; template<> 

class accumulationtraits 

}; template<> 

class accumulationtraits 

}; 

//普通的求和**類

class sumpolicy  };

//普通的求積**類

class multpolicy  };

//trait 和 policy的聯合使用 模板

template

typename traits = accumulationtraits> 

class accum  

return total; 

} }; 

三、使用

int main() ; 

//  列印所有數值的乘積 

std::cout << "the product of the integer values is " 

<< accum::accum(&num[0], &num[5]) 

<< '\n'; 

} 然而上述程式的輸出結果不如預期: 

the product of the integer values is 0 

問題在於我們對初始值的不當選擇:初始值   0   對「求和」而言很合適,對「乘積」來說就不妥 了(初始值為  0,注定乘積結果也是  0)。這也說明了不同的  traits  和  policies  可能相互影響,同時也強調了謹慎設計  templates 的重要性。 

從這個例子中我們可以意識到,accumulation   loop(累計迴圈)的初始化應該成為   accumulation policy  的乙個成份。這個  policy  可以使用也可以不使用  trait   zero()。其它替代方案也不該被遺忘   ―   並不是什麼事都非得使用  traits  和  policies  解決不可。c++   標準庫的accumulate()就是接受第三個  call argument 做為初始值

c 類模板的簡單使用

include define elmtpe char 在此修改要處理的資料型別 using namespace std 引用的函式原型 class compare int max int min int compare max int compare min template 宣告乙個模板,虛擬型別...

類模板的使用 類模板使用總結

歸納以上的介紹,可以這樣宣告和使用類模板 先寫出乙個實際的類。將此類中準備改變的型別名 如int要改變為float或char 改用乙個自己指定的虛擬型別名 如上例中的t 在類宣告前面加入一行,格式為 templatetemplate class a 類體用類模板定義物件時用以下形式 類模板名 實際型...

簡單類模板

include include struct student 結構體student template 類模板 實現對任意型別資料進行訪問 class store template store store template t store getelem int main stores1,s2 sto...