1
0

tmp2tmp.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // tmp2tmp.cpp -- template friends to a template class
  2. #include <iostream>
  3. using std::cout;
  4. using std::endl;
  5. // template prototypes
  6. template <typename T> void counts();
  7. template <typename T> void report(T &);
  8. // template class
  9. template <typename TT>
  10. class HasFriendT
  11. {
  12. private:
  13. TT item;
  14. static int ct;
  15. public:
  16. HasFriendT(const TT & i) : item(i) {ct++;}
  17. ~HasFriendT() { ct--; }
  18. friend void counts<TT>();
  19. friend void report<>(HasFriendT<TT> &);
  20. };
  21. template <typename T>
  22. int HasFriendT<T>::ct = 0;
  23. // template friend functions definitions
  24. template <typename T>
  25. void counts()
  26. {
  27. cout << "template size: " << sizeof(HasFriendT<T>) << "; ";
  28. cout << "template counts(): " << HasFriendT<T>::ct << endl;
  29. }
  30. template <typename T>
  31. void report(T & hf)
  32. {
  33. cout << hf.item << endl;
  34. }
  35. int main()
  36. {
  37. counts<int>();
  38. HasFriendT<int> hfi1(10);
  39. HasFriendT<int> hfi2(20);
  40. HasFriendT<double> hfdb(10.5);
  41. report(hfi1); // generate report(HasFriendT<int> &)
  42. report(hfi2); // generate report(HasFriendT<int> &)
  43. report(hfdb); // generate report(HasFriendT<double> &)
  44. cout << "counts<int>() output:\n";
  45. counts<int>();
  46. cout << "counts<double>() output:\n";
  47. counts<double>();
  48. // std::cin.get();
  49. return 0;
  50. }