You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据运行时条件选择不同变长参数函子简化打印逻辑?

如何实现仅赋值一次且无每次调用判断的verbose打印函子?

我有一个运行时布尔值verbose,当它为false时会取消部分标准输出打印。现有大量如下结构的代码:

void add(const int a, const int b, const bool verbose)
{
    //...
    if(verbose) std::print("{}+{}={}\n", a, b, a+b);
}

我的目标是实现如下形式的代码:

template<typename F>
void add(const int a, const int b, F print_if_verbose)
{
    //...
    print_if_verbose("{}+{}={}\n", a, b, a+b);
}

这么做的目的是简化代码、降低出错概率(避免每次打印都忘记判断verbose),同时让各个子系统无需感知verbose参数。

我的初步尝试如下:

template<typename F>
void add(const int a, const int b, F print_if_verbose)
{
    print_if_verbose("{}+{}={}\n", a, b, a+b);
}

int main(const int, const char* const argv[])
{
    const bool verbose = get_verbose_arg(); // runtime boolean

    // 无法编译,类型不匹配
    //const auto vprint = verbose ? [](const std::string_view msg, const auto&... args){std::vprint_unicode(msg, std::make_format_args(args...));}
    //                            : [](const std::string_view, const auto&...){};
    //add(1, 2, vprint);

    // 可行但写法繁琐
    const auto verb_print = [](const std::string_view msg, const auto&... args){ std::vprint_unicode(msg, std::make_format_args(args...)); };
    const auto no_print = [](const std::string_view, const auto&...){};
    if(verbose) add(2, 3, verb_print);
    else        add(2, 3, no_print);

    // 可行但每次调用都会判断verbose
    const auto maybe_print = [verb=verbose](const std::string_view msg, const auto&... args){ if(verb) std::vprint_unicode(msg, std::make_format_args(args...)); };
    add(3, 4, maybe_print);
}

请问是否存在我遗漏的方法,能够仅赋值一次函子,且无需每次调用都判断verbose?

内容的提问来源于stack exchange,提问作者MatG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 12:50:15