Why extra brackets in the file reader function?

I understand that the following code ( here ) is used to read the contents of a file in a line:

#include <fstream> #include <string> std::ifstream ifs("myfile.txt"); std::string content( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) ); 

However, I do not understand why such seemingly redundant brackets 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 required to compile?

+7
source share
1 answer

Because without parentheses, the compiler treats this as a function declaration, declaring a function called content that returns std::string and takes as arguments a std::istreambuf_iterator<char> with the name ifs and an alias that is a function that takes no arguments, returning a std::istreambuf_iterator<char> .

You can either live with partners, or as Alexander’s notes in the comments, you can use a single C ++ initialization function that does not have such ambiguities:

 std::string content { std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() }; 

Or as Loki mentions:

 std::string content = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()); 
+12
source

All Articles