decltype(std::cin)&& is = (argc < 2 ? std::move(std::cin) : std::ifstream(argv[1]));
Is this dangerous? Is there a simpler/less dangerous way?
It works fine. Example:
int i = 42;
is >> i; // enter 50
std::cout << i; // 50
decltype(std::cin)&& is = (argc < 2 ? std::move(std::cin) : std::ifstream(argv[1]));
Is this dangerous? Is there a simpler/less dangerous way?
It works fine. Example:
int i = 42;
is >> i; // enter 50
std::cout << i; // 50
I can't speak to exactly how safe your version is. However, personally, I wouldn't want to move std::cin
or bind to an std::ifstream
unless I knew it was open(able). I favour opening the std::ifstream
first (if it has been specified in the argv
) and then binding to a std::istream&
if is_open()
else bind to std::cin
.
I do this all the time and it is perfectly safe:
int main(int argc, char* argv[])
{
std::ifstream ifs;
if(argc > 1)
{
ifs.open(argv[1]);
// check error and maybe exit
}
std::istream& is = ifs.is_open() ? ifs : std::cin;
// ...
}
The answers to this SO question may also be of interest.