C++ > templates > なるべく参照渡しにしよう

なるべく参照渡しにしよう

copyright/C++ Templates - The Complete Guide

  1. // maximum of two values of any type (call-by-reference)
  2. template <typename T>
  3. inline T const& max (T const& a, T const& b){
  4. return a < b ? b : a;
  5. }
  6.  
  7. // maximum of two C-strings (call-by-value)
  8. inline char const* max (char const* a, char const* b){
  9. return std::strcmp(a,b) < 0 ? b : a;
  10. }
  11.  
  12. // maximum of three values of any type (call-by-reference)
  13. template <typename T>
  14. inline T const& max (T const& a, T const& b, T const& c){
  15. return max (max(a,b), c); // error, if max(a,b) uses call-by-value
  16. }
  17.  
  18. int main (){
  19. ::max(7, 42, 68); // OK
  20.  
  21. const char* s1 = "frederic";
  22. const char* s2 = "anica";
  23. const char* s3 = "lucas";
  24. ::max(s1, s2, s3) // ERROR

GCCではエラーにはなりませんでしたが、たぶん危険なので注意しよう。

最終更新:2007年11月21日 11:27
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。