Creating an instance of an ifstream object without using a variable

I cannot open a file without saving it in a variable. I can do it:

ifstream blob("somefile"); string line; blob >> line; 

But when I try this:

 string line; ifstream("somefile") >> line; 

The compiler (clang) gives this error:

 t.cpp:7:23: error: invalid operands to binary expression ('ifstream' (aka 'basic_ifstream<char>') and 'string' (aka 'basic_string<char>')) ifstream("thing") >> i; ~~~~~~~~~~~~~~~~~ ^ ~ In file included from t.cpp:1: In file included from /usr/include/c++/4.6/iostream:39: In file included from /usr/include/c++/4.6/ostream:39: In file included from /usr/include/c++/4.6/ios:42: In file included from /usr/include/c++/4.6/bits/ios_base.h:42: In file included from /usr/include/c++/4.6/bits/locale_classes.h:41: In file included from /usr/include/c++/4.6/string:53: /usr/include/c++/4.6/bits/basic_string.h:2679:5: note: candidate function [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>] not viable: no known conversion from 'ifstream' (aka 'basic_ifstream<char>') to 'basic_istream<char> &' for 1st argument operator>>(basic_istream<char>& __is, basic_string<char>& __str); ^ In file included from t.cpp:1: In file included from /usr/include/c++/4.6/iostream:40: / usr/include/c++/4.6/istream:121:7: note: candidate function not viable: no known conversion from 'string' (aka 'basic_string<char>') to '__istream_type &(*)(__istream_type &)' for 1st argument operator>>(__istream_type& (*__pf)(__istream_type&)) ^ /usr/include/c++/4.6/istream:125:7: note: candidate function not viable: no known conversion ... a few more hundred pages of crap ... 1 error generated. 

So what's the difference between the two? With other classes, calling it directly works just fine. Is there some kind of template magic that makes it ambiguous?

+4
source share
1 answer

The code you publish is not valid in C ++ 03 (that is, what was the C ++ language standard until September 2011). In C ++ 03, there is only one operator>> overload, which can be considered here. [I deleted all the template code because it doesn't matter]:

 istream& operator>>(istream&, string&); 

Note that the std::istream is a non-constant reference, so you cannot use the temporary std::istream . In your code, you are trying to use a temporary object there.

In C ++ 11 (i.e., the current C ++ language language) there is an additional overload that takes an std::istream by rvalue reference. This allows you to either temporarily pass through this parameter.

Visual C ++ already supports this C ++ 11 feature, so, as Benjamin Lindley points out in a comment, your code will really compile if you use Visual C ++ 2010 or later. Your Clang assembly can support this if you use the -std = C ++ 0x flag.

+3
source

Source: https://habr.com/ru/post/1379739/


All Articles