-1

How does std::cin object deal with different types while it is an instance of basic_istream<char> (istream)?

asmmo
  • 6,922
  • 1
  • 11
  • 25
  • Do you understand how `cout` can accept different types, like `int` and `std::string`. What then if you have `struct S {};` will `cin` or `cout` accept either of those? – Tas Jun 27 '18 at 06:15
  • No, `cin` and `cout` would not accept `S` unless I defineded an operator to deal with `S` but `cin` and `cout`deal with `int` and `std::string` well. – asmmo Jun 27 '18 at 06:17
  • Look at [gcc's istream source code](https://gcc.gnu.org/onlinedocs/gcc-4.6.3/libstdc++/api/a00912_source.html). – An0num0us Jun 27 '18 at 06:22
  • I don't understand how `istream` accepts all of the fundamental types while it is a `char` instance of the template `basic_istream` @NickyC – asmmo Jun 27 '18 at 06:25
  • That's basic C++: [operator overloading](https://en.cppreference.com/w/cpp/language/operators) – Adrian W Jun 27 '18 at 06:26
  • @AsmM What do you mean by "accepts"? –  Jun 27 '18 at 06:32

1 Answers1

3

The class std::basic_istream<CharT, Traits> models an input stream of characters of type CharT. It provides both relatively low-level and relatively high-level access to that input stream. You can, for example, call std::cin.get() in order to retrieve the next character from the input stream; this will always return CharT, since that's the underlying type of characters in the stream. However, basic_istream also provides the formatted input functions, whose purpose is to interpret that character stream as an encoding of some type, which could potentially be int, std::basic_string<CharT, Traits>, or something else. Thus, while the stream does not consist of ints, there is an operator>> that extracts an int value by reading digits successively from a char stream and interpreting them as the base-10 representation of an integer. The operator>> function is overloaded so that it can be used to extract various different types.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312