fork 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. template <class T>
  38. class GenericReadable : public IReadable {
  39. T & t_;
  40. public:
  41. GenericReadable(T& t) : t_(t) {};
  42. virtual IReadable& read(char *p,int n) {
  43. t_.read(p, n);
  44. return *this;
  45. };
  46. };
  47.  
  48. template <class T>
  49. GenericReadable<T> make_readable(T& t) {
  50. return GenericReadable<T>(t);
  51. };
  52.  
  53. int main(int argc,char **argv)
  54. {
  55. std::ifstream file("foo.bar",std::ifstream::binary);
  56. auto fileReadable = make_readable(file);
  57.  
  58. CFileReader file_reader(fileReadable);
  59. CMemoryReader memory_reader;
  60.  
  61. auto memReadable = make_readable(memory_reader);
  62.  
  63. std::vector<IReadable*> vv;
  64. vv.push_back(&file_reader);
  65. vv.push_back(&memReadable);
  66. char buff[8];
  67.  
  68. for(auto& reader : vv)
  69. {
  70. reader->read(buff,4);
  71. }
  72. return 0;
  73. }
Success #stdin #stdout 0s 4348KB
stdin
Standard input is empty
stdout
Standard output is empty