I understand that the following code (from here) is used to read the contents of a file to string:
#include <fstream>
#include <string>
std::ifstream ifs("myfile.txt");
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
However, I don’t understand why such seemingly redundant parentheticals are required. For example, the following code does not compile:
#include <fstream>
#include <string>
std::ifstream ifs("myfile.txt");
std::string content(std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>() );
Why are so many parentheses are needed for this to compile?
Because without the parentheses, the compiler treats it as a function declaration, declaring a function named
contentthat returns astd::stringand takes as arguments astd::istreambuf_iterator<char>namedifsand a nameless parameter that is a function taking no arguments that returns astd::istreambuf_iterator<char>.You can either live with the parens, or as Alexandre notes in the comments, you can use the uniform initialisation feature of C++ which has no such ambiguities:
Or as Loki mentions: