如何根据运行时条件选择不同变长参数函子简化打印逻辑?
如何实现仅赋值一次且无每次调用判断的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
相关产品推荐
相关产品推荐

