1

外部ツールを使用するログ ライブラリを作成しようとしています。

ライブラリを使用するプログラマーへの影響を最小限に抑えながら、外部ツールによる解析を支援するためにキー文字列を出力ストリームに追加する便利な方法を探しています

目標は、次のようなものを達成することです。

cout << DEBUG::VERBOSE << "A should equal 3" << endl;
cout << DEBUG::WARNING << "something went wrong" << endl;

今のところ、次のようにデータを構造化しました

struct Debug
{
static const std::string FATAL_ERROR; 
static const std::string ERROR;
static const std::string WARNING;
static const std::string IMPORTANT;
static const std::string INFORMATION;
static const std::string VERBOSE;
static const std::string DEBUG;
};

std::stringこれは機能しますが、タイプから抽象化のレベルを追加したいと思います。

Java/C# ではenum、書き込み動作を実現するために を使用できますが、これを C++ でエレガントに実装するにはどうすればよいでしょうか。

4

1 に答える 1

5

endlC++ iostream では、次のスタイルのストリーム マニピュレータがより慣用的であると思います。

#include <iostream>

namespace debug
{
    std::ostream & info(std::ostream & os) { return os << "Info: "; }
    std::ostream & warn(std::ostream & os) { return os << "Warning: "; }
    std::ostream & error(std::ostream & os) { return os << "Error: "; }
}

int main()
{
    std::cout << debug::info << "This is main()\n"
              << debug::error << "Everything is broken\n";
}
于 2013-04-09T00:39:50.340 に答える