fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. //Forward declarations
  5. template< typename T >
  6. class Container;
  7. template< typename T, typename charT, typename traits >
  8. basic_ostream< charT, traits >&
  9. operator<<( basic_ostream< charT, traits >& out,
  10. const Container< T >& a_container );
  11.  
  12. //Definitions
  13. template< typename T >
  14. class Container
  15. {
  16. public:
  17. Container( T a_value ): value( a_value ){}
  18.  
  19. private:
  20. T value;
  21.  
  22. template< typename T2, typename charT, typename traits >
  23. friend basic_ostream< charT, traits >&
  24. operator<<( basic_ostream< charT, traits >& out,
  25. const Container< T2 >& a_container );
  26. };
  27.  
  28. template< typename T, typename charT, typename traits >
  29. basic_ostream< charT, traits >&
  30. operator<<( basic_ostream< charT, traits >& out,
  31. const Container< T >& a_container )
  32. {
  33. static_assert(std::is_same<T, int>::value, "Error: T must be an integer");
  34. out << a_container.value;
  35. return out;
  36. }
  37.  
  38. //Main
  39. int main( void )
  40. {
  41. Container< int > my_container( 42 );
  42. Container<bool> other(100);
  43.  
  44. cout << my_container;
  45. cout << other; // ERROR
  46.  
  47. return 0;
  48. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In instantiation of ‘std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>&, const Container<T>&) [with T = bool; charT = char; traits = std::char_traits<char>]’:
prog.cpp:45:13:   required from here
prog.cpp:33:5: error: static assertion failed: Error: T must be an integer
     static_assert(std::is_same<T, int>::value, "Error: T must be an integer");
     ^
stdout
Standard output is empty