默认“NULL"一个 ofstream 的值 [英] Default "NULL" value for an ofstream

查看:83
本文介绍了默认“NULL"一个 ofstream 的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个功能

int myfun(const int a) {
    ...
    return rval;
}

执行多个操作.

我的意思是根据我可以传递的一些参数来调整它以编写有关其行为的调试信息或不编写调试信息.在我想编写该信息的情况下,我还想传递 ofstream 以使用.而且我希望使用 myfun 的应用程序仍然可以工作,无需修改.

I mean to adapt it to write debug information on its behaviour or not according to some parameter that I can pass. In the cases I want to write that info, I also want to pass the ofstream to use. And I want applications that were using myfun to still work with no modifications.

所以我最好改为

int myfun(const int a, ofstream & ofs) {
    ...
    if (!(ofs == NULL)) {
        ofs << ...
    }
    ...
    if (!(ofs == NULL)) {
        ofs << ...
    }
    return rval;
}

具有类似于 &ofs=NULL 的默认值.我知道 NULL 不合适.

with a default value similar to &ofs=NULL. I know NULL is not appropriate.

处理这个问题的合适方法是什么?

注意 1:我可以传递一个带有输出文件名的可选参数,但这不太灵活.

Note 1: I could pass an optional parameter with the output file name, but that is less flexible.

注意 2:我也可以改成

int myfun(const int a, const bool debug_info, ofstream & ofs) {
    ...
    if (debug_info) {
        ofs << ...
    }

具有默认值 debug_info=false.我想这仍然需要 ofs 的默认值,如上所述.

with a default value debug_info=false. I guess this still requires a default value for ofs as above.

注意 3:函数中的默认 ofstream 类参数 中接受的答案提出了一个没有 ofs 参数.在我的情况下,这可能不起作用,因为我的意思是在ofs=NULL"时不写任何内容.

Note 3: The accepted answer in Default ofstream class argument in function proposes an overload without the ofs parameter. In my case that may not work, as I mean to not write anything when "ofs=NULL".

注意 4:这个其他答案显然有效,但对我来说似乎有些人为,我不确定它提供的所有功能与传递一个 ofs.

Note 4: This other answer apparently works, but it seems somewhat contrived to me, and I am not sure it provides all the same functionality as with passing an ofs.

相关:

是否有空 std::ostream 在 C++ 或库中实现?

推荐答案

我希望使用 myfun 的应用程序仍然可以工作,无需修改.

I want applications that were using myfun to still work with no modifications.

如果是这样,使用默认 nullptr

If so, use an ofs with default nullptr

int myfun(const int a, ofstream *ofs = nullptr)
{
    if (ofs != nullptr)
    {
        // (*ofs) << ... ;
    }

    // ...
}

您不能使用参考参数 ofstream&ofs 因为引用不能为空.

You can't use a reference parameter ofstream& ofs for such function because a reference cannot be null.

这篇关于默认“NULL"一个 ofstream 的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆