I found somewhere the following idiom for reading a file into a string:
std::ifstream file("path/to/some/file.ext");
std::string contents(
std::istreambuf_iterator<char>(file),
(std::istreambuf_iterator<char>())
);
Which works just fine as it is. However, if I remove the parentheses around the second iterator argument, that is:
std::string contents(
std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>()
);
As soon as I try to call any method on the string object, for example:
const char *buffer = contents.c_str();
I get a compile error of the form:
error: request for member 'c_str' in 'contents', which is of non-class type 'std::string(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)()) {aka std::basic_string<char>(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)())}'
Also if I try to assign that string to another:
std::string contents2 = contents;
I get an error of the form:
error: conversion from 'std::string(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)()) {aka std::basic_string<char>(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)())}' to non-scalar type 'std::string {aka std::basic_string<char>}' requested
Why is this? I can see no reason for those parentheses being needed, much less affect the type definition of the contents
variable. I am using g++ 4.8.2.