frnd2tmp.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // frnd2tmp.cpp -- template class with non-template friends
  2. #include <iostream>
  3. using std::cout;
  4. using std::endl;
  5. template <typename T>
  6. class HasFriend
  7. {
  8. private:
  9. T item;
  10. static int ct;
  11. public:
  12. HasFriend(const T & i) : item(i) {ct++;}
  13. ~HasFriend() {ct--; }
  14. friend void counts();
  15. friend void reports(HasFriend<T> &); // template parameter
  16. };
  17. // each specialization has its own static data member
  18. template <typename T>
  19. int HasFriend<T>::ct = 0;
  20. // non-template friend to all HasFriend<T> classes
  21. void counts()
  22. {
  23. cout << "int count: " << HasFriend<int>::ct << "; ";
  24. cout << "double count: " << HasFriend<double>::ct << endl;
  25. }
  26. // non-template friend to the HasFriend<int> class
  27. void reports(HasFriend<int> & hf)
  28. {
  29. cout <<"HasFriend<int>: " << hf.item << endl;
  30. }
  31. // non-template friend to the HasFriend<double> class
  32. void reports(HasFriend<double> & hf)
  33. {
  34. cout <<"HasFriend<double>: " << hf.item << endl;
  35. }
  36. int main()
  37. {
  38. cout << "No objects declared: ";
  39. counts();
  40. HasFriend<int> hfi1(10);
  41. cout << "After hfi1 declared: ";
  42. counts();
  43. HasFriend<int> hfi2(20);
  44. cout << "After hfi2 declared: ";
  45. counts();
  46. HasFriend<double> hfdb(10.5);
  47. cout << "After hfdb declared: ";
  48. counts();
  49. reports(hfi1);
  50. reports(hfi2);
  51. reports(hfdb);
  52. // std::cin.get();
  53. return 0;
  54. }