首页 > 解决方案 > 在 std::ifstream 上调用 set_rdbuf 和 rdbuf 时出错

问题描述

标签: c++

解决方案


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!


推荐阅读