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

Deadly 提交于 2019-12-12 13:35:19

问题


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?


回答1:


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.




回答2:


It looks like one of the examples for "C++ most vexing parse" problem. Looks like compiler is interpreting the statement with () as a function declaration of function str which accepts two parameters. By adding () you are informing the compiler that it is an object and not part of function prototype signature.



来源:https://stackoverflow.com/questions/10039657/strange-error-in-using-templateclass-inputiterator-string-inputiterator-begin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!