fork(2) download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4.  
  5. class IReadable
  6. {
  7. public:
  8. IReadable(){};
  9. virtual ~IReadable(){};
  10. virtual IReadable& read(char *p,int n) = 0;
  11. };
  12.  
  13. class CFileReader: public IReadable
  14. {
  15. public:
  16. template <class T>
  17. CFileReader(T& v) : obj(&v) {};
  18. ~CFileReader(){};
  19. IReadable& read(char *p,int n) {
  20. this->obj->read(p,n);
  21. return *(this->obj);
  22. }
  23. private:
  24. IReadable* obj;
  25. };
  26.  
  27. class CMemoryReader
  28. {
  29. public:
  30. CMemoryReader(){};
  31. ~CMemoryReader(){};
  32. CMemoryReader& read(char *p,int n) { return *this; }; // do nothing
  33. private:
  34. char *mem;
  35. };
  36.  
  37. int main(int argc,char **argv)
  38. {
  39. std::ifstream file("foo.bar",std::ifstream::binary);
  40. CFileReader file_reader(&file);
  41. CMemoryReader memory_reader;
  42. std::vector<IReadable*> vv;
  43. vv.push_back(&file_reader);
  44. vv.push_back(&memory_reader);
  45. char buff[8];
  46.  
  47. for(auto& reader : vv)
  48. {
  49. reader->read(buff,4);
  50. }
  51. return 0;
  52. }
  53.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:40:26: error: invalid initialization of non-const reference of type ‘std::basic_ifstream<char>*&’ from an rvalue of type ‘std::ifstream* {aka std::basic_ifstream<char>*}’
  CFileReader file_reader(&file);
                          ^~~~~
prog.cpp:17:2: note:   initializing argument 1 of ‘CFileReader::CFileReader(T&) [with T = std::basic_ifstream<char>*]’
  CFileReader(T& v) : obj(&v) {};
  ^~~~~~~~~~~
prog.cpp:44:29: error: no matching function for call to ‘std::vector<IReadable*>::push_back(CMemoryReader*)’
  vv.push_back(&memory_reader);
                             ^
In file included from /usr/include/c++/6/vector:64:0,
                 from prog.cpp:3:
/usr/include/c++/6/bits/stl_vector.h:914:7: note: candidate: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = IReadable*; _Alloc = std::allocator<IReadable*>; std::vector<_Tp, _Alloc>::value_type = IReadable*]
       push_back(const value_type& __x)
       ^~~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:914:7: note:   no known conversion for argument 1 from ‘CMemoryReader*’ to ‘IReadable* const&’
/usr/include/c++/6/bits/stl_vector.h:932:7: note: candidate: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = IReadable*; _Alloc = std::allocator<IReadable*>; std::vector<_Tp, _Alloc>::value_type = IReadable*]
       push_back(value_type&& __x)
       ^~~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:932:7: note:   no known conversion for argument 1 from ‘CMemoryReader*’ to ‘IReadable*&&’
stdout
Standard output is empty