1. #include <iostream>
  2.  
  3. struct point_tag {};
  4. struct vector_tag {};
  5.  
  6. struct Point {
  7. typedef point_tag type;
  8. };
  9.  
  10. struct Vector {
  11. typedef vector_tag type;
  12. };
  13.  
  14. // Point用 print
  15. void print_(const Point& target, point_tag) {
  16. std::cout << "Point\n";
  17. }
  18.  
  19. // Vector用 print
  20. void print_(const Vector& target, vector_tag) {
  21. std::cout << "Vector\n";
  22. }
  23.  
  24. // Point/Vector用print
  25. template <typename Arg>
  26. void print( const Arg &x ) {
  27. print_( x, typename Arg::type() ); // Arg::type で上記のどっちかに振り分ける
  28. }
  29.  
  30. int main() {
  31. Point p;
  32. Vector v;
  33. print(p);
  34. print(v);
  35. }
  36.  

タグ:

C++ Tips Technique
最終更新:2008年01月09日 20:33