C++ 从std::istreambuf_迭代器创建std::string,奇怪的语法怪癖
我在某处找到了以下将文件读入字符串的习惯用法:C++ 从std::istreambuf_迭代器创建std::string,奇怪的语法怪癖,c++,stl,C++,Stl,我在某处找到了以下将文件读入字符串的习惯用法: std::ifstream file("path/to/some/file.ext"); std::string contents( std::istreambuf_iterator<char>(file), (std::istreambuf_iterator<char>()) ); 我得到一个编译错误: 错误:请求“contents”中的成员“c_str”,该成员属于非类类型“std::string(st
std::ifstream file("path/to/some/file.ext");
std::string contents(
std::istreambuf_iterator<char>(file),
(std::istreambuf_iterator<char>())
);
我得到一个编译错误:
错误:请求“contents”中的成员“c_str”,该成员属于非类类型“std::string(std::istreambuf_迭代器,std::istreambuf_迭代器(*)()”{aka std::basic_string(std::istreambuf_迭代器,std::istreambuf_迭代器(*)()}
如果我尝试将该字符串分配给另一个字符串:
std::string contents2 = contents;
我得到一个表单错误:
错误:请求从'std::string(std::istreambuf_迭代器,std::istreambuf_迭代器(*)(){aka std::basic_string(std::istreambuf_迭代器,std::istreambuf_迭代器(*)()}转换为非标量类型'std::string{aka std::basic_string}
为什么会这样?我看不出需要这些括号的原因,更不用说影响contents
变量的类型定义了。我使用的是g++4.8.2。这是以下示例:
这里有很多最烦人的解析问题,但都很相似。只要你知道什么是最烦人的解析,这就很好了。如果你没有(就像我没有),甚至很难知道该找什么。这就是为什么我决定问这个问题。
const char *buffer = contents.c_str();
std::string contents2 = contents;
std::string contents(
std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>()
);
std::string contents{std::istreambuf_iterator<char>{file}, {}};