How can I redirect a std::ofstream to std::cout?

假如想象 提交于 2020-01-03 14:18:11

问题


I'm working with some code that uses a global debug logger that is of type std::ofstream*. I would like to redirect this to std::cout since I'm using the code in realtime, as opposed to a batch method for which it was designed.

Is it possible to redirect the global std::ofstream* pointer it uses to std::cout? I know std::ofstream inherits from std::ios, which allows one to change the stream buffer using the rdbuf() method, but unfortunately it appears std::ofstream redefines the rdbuf() method, which makes the following code not compile:

gOsTrace = new std::ofstream();
gOsTrace->rdbuf(std::cout.rdbuf());

Is there another way to redirect the gOsTrace object to point to cout?


回答1:


The rdbuf() method of the concrete IOStream stream classes hide the one declared in std::ios. You will need an explicit qualification in order to find the base class overload:

gOsTrace->basic_ios<char>::rdbuf(std::cout.rdbuf());


来源:https://stackoverflow.com/questions/31865677/how-can-i-redirect-a-stdofstream-to-stdcout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!