特定のプログラム条件に応じて、a をオブジェクトまたはstd::ostream
オブジェクトにバインドするにはどうすればよいですか? これは多くの理由で無効ですが、意味的には次のものと同等のものを実現したいと考えています。std::cout
std::ofstream
std::ostream out = condition ? &std::cout : std::ofstream(filename);
http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.htmlの例など、例外セーフではない例をいくつか見ました。
int main(int argc, char *argv[])
{
std::ostream* fp; //1
if (argc > 1)
fp = new std::ofstream(argv[1]); //2
else
fp = &std::cout //3
*fp << "Hello world!" << std::endl; //4
if (fp!=&std::cout)
delete fp;
}
より優れた例外セーフなソリューションを知っている人はいますか?