Why does std::istringstream appear to resolve differently to std::ifstream in the ternary (?:) operator?

后端 未结 4 1800
情歌与酒
情歌与酒 2020-11-30 09:42

I am used to writing little command line tools that take either a file name or read from std::cin, so I have been using this pattern for quite a while:

4条回答
  •  爱一瞬间的悲伤
    2020-11-30 10:31

    The compiler tries to find a common type for both result from the ternary operator, and if you see e.g. this reference you will see there is a casting operator override for void* (or bool for C++11 and later), so the compiler uses that.

    But then when it tries to do the assignment, it errors out because on the right-hand side of the initialization you have a void* (alternatively bool) type, and on the left-hand side there's a reference to std::istream.

    To solve it you have to manually cast each stream to a reference to std::istream with e.g. static_cast.

提交回复
热议问题