例のタイムスタンプはそれだけでした、例:)。
しかし、それが気に入れば、実装を試みることができます。C++11 とその STL の大幅な改善のおかげで、優れた時刻/日付 API: std::chronoを利用できます。
std::chrono次の 3 つの側面に基づいています。
また、chrono には 、 、 の 3 種類のクロックが用意されstd::system_clockています。私たちの場合、(正確な時間間隔を測定するのではなく、日時にアクセスしたい) を使用します。
std::chrono の詳細については、このすばらしい Bo Qian の youtube チュートリアル を参照してください。std::steady_clockstd::high_resolution_clockstd::system_clock
したがって、ログ ヘッダーにタイム スタンプを実装する必要がある場合は、次のようにすることができます。
編集:他の優れた機能と同様に、C++ テンプレートは使いすぎない限り優れたツールです。
私たちの問題std::endlは、テンプレート化された関数であるoperator<<ため、コンパイラが std::endl テンプレート引数を直接推測できないため、別のテンプレート化された関数にパラメーター (この場合) として直接渡すことができないことでした。それは、 「未解決のオーバーロードされた関数型」という再発エラーです。
しかし、これを行うためのはるかに簡単な方法があります: for onlyの明示的なオーバーロードを使用し、他のすべてのテンプレート化された other を使用します。operator<<std::endl
class Log
{
private:
std::ostream& _out_stream;
bool _next_is_begin;
const std::string _log_header;
using endl_type = decltype( std::endl ); //This is the key: std::endl is a template function, and this is the signature of that function (For std::ostream).
public:
static const std::string default_log_header;
//Constructor: User passes a custom log header and output stream, or uses defaults.
Log(const std::string& log_header = default_log_header , std::ostream& out_stream = std::cout) : _log_header( log_header ) , _out_stream( out_stream ) , _next_is_begin( true ) {}
//Overload for std::endl only:
Log& operator<<(endl_type endl)
{
_next_is_begin = true;
_out_stream << endl;
return *this;
}
//Overload for anything else:
template<typename T>
Log& operator<< (const T& data)
{
auto now = std::chrono::system_clock::now();
auto now_time_t = std::chrono::system_clock::to_time_t( now ); //Uhhg, C APIs...
auto now_tm = std::localtime( &now_time_t ); //More uhhg, C style...
if( _next_is_begin )
_out_stream << _log_header << "(" << now_tm->tm_hour << ":" << now_tm->tm_min << ":" << now_tm->tm_sec << "): " << data;
else
_out_stream << data;
_next_is_begin = false;
return *this;
}
};
const std::string Log::default_log_header = "Log entry";
このコード スニペットは完全に機能します。完全な実装を github アカウントにプッシュしました。
参照: