From 39a938cc20d267f6623901d2d559ec881e654d55 Mon Sep 17 00:00:00 2001 From: Roland Conybeare Date: Tue, 20 Jan 2026 16:40:43 -0500 Subject: [PATCH] xo-indentlog: + cond feature --- .../include/xo/indentlog/print/cond.hpp | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 xo-indentlog/include/xo/indentlog/print/cond.hpp diff --git a/xo-indentlog/include/xo/indentlog/print/cond.hpp b/xo-indentlog/include/xo/indentlog/print/cond.hpp new file mode 100644 index 00000000..de3a13e7 --- /dev/null +++ b/xo-indentlog/include/xo/indentlog/print/cond.hpp @@ -0,0 +1,92 @@ +/** @file cond.hpp + * + * author: Roland Conybeare + **/ + +#pragma once + +#include "ppdetail_atomic.hpp" +#include +#include + +namespace xo { + + /** @class cond_impl + * @brief conditional stream inserter implementation + * + * @tparam T type printed when condition is true + * @tparam U type printed when condition is false + **/ + template + struct cond_impl { + public: + cond_impl(bool condition, T const & then_value, U const & else_value) + : condition_{condition}, + then_value_{then_value}, + else_value_{else_value} {} + + bool condition() const { return condition_; } + T const & then_value() const { return then_value_; } + U const & else_value() const { return else_value_; } + + private: + bool condition_; + T then_value_; + U else_value_; + }; + + /** Create conditional stream inserter. + * + * @param condition when true, print @p then_value; otherwise print @p else_value + * @param then_value value to print when condition is true + * @param else_value value to print when condition is false + * + * Example: + * @code + * std::cout << cond(ptr != nullptr, xtag("ptr", *ptr), "nullptr"); + * @endcode + **/ + template + auto + cond(bool condition, T && then_value, U && else_value) + { + return cond_impl, std::decay_t> + (condition, + std::forward(then_value), + std::forward(else_value)); + } + + /** Stream insertion operator for cond_impl **/ + template + inline std::ostream & + operator<<(std::ostream & os, cond_impl const & c) + { + if (c.condition()) + os << c.then_value(); + else + os << c.else_value(); + return os; + } + +#ifndef ppdetail_atomic + namespace print { + /** Pretty-printing support for cond_impl **/ + template + struct ppdetail> { + using target_type = cond_impl; + + static bool print_pretty(const ppindentinfo & ppii, + const target_type & c) + { + if (c.condition()) + return ppdetail::print_pretty(ppii, c.then_value()); + else + return ppdetail::print_pretty(ppii, c.else_value()); + } + }; + } +#endif + +} + +/* end cond.hpp */