Search code examples
c++stliteratorstdstringistream-iterator

Strange Error in using template<class InputIterator> string (InputIterator begin, InputIterator end);


Given such a code segment:

#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
using namespace std;
int main(){
    ifstream file("1.txt");
    string str((istream_iterator<char>(file)),istream_iterator<char>());
    file.close();
    cout<<str<<endl;
}

The code constructs a string from a file using istream_iterator.

Notice that the first parameter of string constructor is enclosed with a pair of parentheses. If I omit the parentheses, there will be an error. In VC++ 2008, a link error will come about. In G++, the code has a wrong output.

I feel very strange about the parentheses. What's the difference and why?


Solution

  • Without the "extra" parentheses, you get C++'s "most vexing parse" -- instead of defining an object named str with the two istream_iterators to specify its initializers, it's parsed as a declaration of a function named str that returns a string, and the "stuff" in parentheses specifies the types of parameters it takes.