Why are extra parenthesis in file read function?

岁酱吖の 提交于 2019-12-20 14:12:51

问题


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?


回答1:


Because without the parentheses, the compiler treats it as a function declaration, declaring a function named content that returns a std::string and takes as arguments a std::istreambuf_iterator<char> named ifs and a nameless parameter that is a function taking no arguments that returns a std::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:

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>());


来源:https://stackoverflow.com/questions/12590050/why-are-extra-parenthesis-in-file-read-function

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