c++ - 在 std::ifstream 上调用 set_rdbuf 和 rdbuf 时出错
问题描述
解决方案
This is quite interesting. As others have noted, the initial issue here is that the set_rdbuf
member function is protected, so you can’t call it directly. I was surprised when you reported that calling the correct member function rdbuf
didn’t compile, because that member function does exist and is public.
The short version is that I believe the following code will do what you want:
if (path.empty()) objfile.istream::rdbuf(objstr.rdbuf());
The reason you need the istream::
prefix here has to do with how C++ does name lookups in derived classes. If a derived class declares a member function with a given name and you try to call a function with that name, the compiler will not look to base classes to find potential overloads for that function. In C++11, the ifstream
type had a new helper function added called rdbuf
that returns the underlying buffer as a filebuf*
. This shadows the istream
function rdbuf
that sets the underlying buffer. As a result, if call the one-argument version of rdbuf
, C++ won’t find it because it stops searching as soon as it finds the zero-argument rdbuf
defined in ifstream
. Adding the explicit istream::rdbuf
call tells the compiler to search for this function in istream
first, where it ends up finding the function you want.
Hope this helps!
推荐阅读
- ios - 以编程方式将渐变视图和 UILabel 添加到 UIView 不起作用
- ionic-framework - 为什么 Ionic contacts.find 会冻结我的应用程序?
- javascript - 如何在 JavaScript Uint8Array 中存储字符代码?
- c# - 如果满足条件,则跳过序列化列表元素 (Newtonsoft)
- amazon-web-services - 如何使用 AWS Glue 将位于本地的文件加载到 AWS
- c++ - 如何通过 C++ API 向 tflite 提供多维输入
- c# - 方法 get touch 没有重载需要 0 个参数
- azure-cosmosdb - C# 获取 Cosmos 数据库中的容器列表
- c++ - libQGLViewer如何在不清除缓冲区的情况下进行绘制
- google-bigquery - 使用 bigquery 从 GDELT 收集数据