mercredi 9 juin 2021

How to pass std::cin to a class constructor?

I am trying to create a class which can read input from either a file stream or std::cin:

#include <string>
#include <iostream>
#include <mutex>

class A
{
public:
  explicit A(std::istream& input)
    : input_(input)
  {
    ;
  }

public:
  void doSomething()
  {
    std::string word;
    while (input_ >> word) {
      std::cout << word << std::endl;
    }
  }

private:
  std::istream& input_;

  std::mutex mutex_;
};

int main()
{
  auto a = A(std::cin);
  a.doSomething();
  return 0;
}

But the compiler gives the following output:

~/test/main.cpp: In function ‘int main()’:
~/test/main.cpp:31:22: error: use of deleted function ‘A::A(A&&)’
   auto a = A(std::cin);
                      ^
~/test/main.cpp:5:7: note: ‘A::A(A&&)’ is implicitly deleted because the default definition would be ill-formed:
 class A
       ^
~/test/main.cpp:5:7: error: use of deleted function ‘std::mutex::mutex(const std::mutex&)’
In file included from /usr/include/c++/7/mutex:43:0,
                 from ~/test/main.cpp:3:
/usr/include/c++/7/bits/std_mutex.h:97:5: note: declared here
     mutex(const mutex&) = delete;
     ^~~~~

How should I fix the error? Or generally, how do we create a class that can read input either from a file stream or std::cin?


Edit I fixed the code in the question. There was a typo where input_ was std::stream and @JerryJeremiah was correct in the first comment (that it should be std::istream &).

Aucun commentaire:

Enregistrer un commentaire