Why are extra parenthesis in file read function?

后端 未结 1 1009
我在风中等你
我在风中等你 2021-02-06 07:18

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

#include 
#include 

  std::ifstr         


        
1条回答
  •  心在旅途
    2021-02-06 07:42

    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 named ifs and a nameless parameter that is a function taking no arguments that returns a std::istreambuf_iterator.

    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(ifs), std::istreambuf_iterator() };
    

    Or as Loki mentions:

    std::string content = std::string(std::istreambuf_iterator(ifs), std::istreambuf_iterator());
    

    0 讨论(0)
提交回复
热议问题