ログメッセージの実行時に制御可能なリダイレクトの場合、johnとSjoerdのアイデアを組み合わせた自己完結型のソリューション:
class DebugStream {
private:
class NullStream : public std::ostream {
private:
class NullBuffer : public std::streambuf {
public:
int overflow(int c) override { return c; }
} buffer_;
public:
NullStream() : std::ostream(&buffer_) {}
} null_;
std::ostream &output_;
bool enabled_;
public:
DebugStream(std::ostream &output = std::cout) : output_(output), enabled_(false) {}
void enable(const bool enable) { enabled_ = enable; }
template <typename T> std::ostream& operator<<(const T &arg) {
if (enabled_) return output_ << arg;
else return null_ << arg;
}
};
extern DebugStream debug_stream;
#define TRACE_ENABLE(x) debug_stream.enable(x)
#define TRACELN(x) debug_stream << x << std::endl
#define TRACE(x) debug_stream << x
次に、次のようなことを行うことができます。
TRACELN("The value of x is " << x " and the value of y is " << y);
#define
空のステートメントへのトレースマクロを使用して、リリースバージョンからトレースステートメントを完全に削除することも簡単です。
debug_stream
ただし、グローバルな場所を定義する必要があります。