This code works:
std::ifstream f(mapFilename.c_str());
std::string s = std::string(std::istreambuf_iterator(f), std::istreambuf_iterator(
This is C++'s "most vexing parse." A quick Google for that should turn up lots of hits with lots of details. The basic answer is that yes, the compiler is treating it as a function declaration -- and C++ requires that it do so. There's nothing wrong with your compiler (at least in this respect).
If it's any comfort, you have lots of good company in having run into this. In fact, it's sufficiently common that C++0x is added a new brace-initializer syntax, in large part because it avoids this ambiguity. Using it, you could write something like:
std::string s{std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
That will make it clear that the contents of the braces are intended to be values for initializing s
, not types of parameters to a function named s
. I don't know if Apple has a port of it yet, but gcc accepts the new syntax as of version 4.5 (or so).
Edit: Rereading N3092, Johannes is (as usual) quite correct. The applicable language is (§8.5.4/3/5): "If T has an initializer-list constructor, the argument list consists of the initializer list as a single argument; otherwise, the argument list consists of the elements of the initializer list."
So, since std::string
has an initializer-list constructor, this would attempt to "stuff" the two istreambuf_iterator
s into an initializer list, and pass that to the std::string
ctor that takes an initializer list -- but that would be a type mismatch, so the code can't compile. For some other type type that (unlike std::string
did not have an initializer-list ctor) the transformation above would work (thanks to the "otherwise..." in the quote above). In the case of std::string
, you'd have to use one of the current alternatives such as std::string s = std:string(...)
.
I apologize for the incorrect suggested fix -- in this case, one that's all the worse because it confuses an issue that will probably be excessively confusing on its own, and if anything will need careful clarification, especially over the next few years.