1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

標準出力関数をユーザに委譲する

Posted at

標準出力をユーザ関数に委譲したい

ライブラリ内のエラーメッセージや、開発中のデバッグ文字列を標準出力に流したい場合があります。生のprintf 関数で出力してもリリース時に適切な対処(ライブラリならドキュメントに記載する。デバッグ文字列ならコードをすべて除去する。)をしていれば大抵は大きな問題とはなりません。しかし、開発環境に左右されやすい標準出力の動作は、そのサービスを享受するユーザにできるだけ委譲したほうが無難といえるでしょう。

1. ReportFunctionを定義する

std::printf

int printf( const char* format, ... );

この関数をハンドリングするために、次のような型を用意しておきます。

using ReportFunction = int (*)( const char*, ... );

2. メッセージフォーマットをブリッジする


ReportFunction rf = nullptr; // ex. rf = printf;

template<typename ...Args>
int report( Args ...args )
{
    return ( rf != nullptr ) ? rf( args... ) : 0;
}

可変長引数テンプレートを使うと、簡単にメッセージフォーマットを受け渡すことができます。

使い方

ReportFunction rf に、ユーザの任意の標準出力関数をもらいます。メッセージを構築する側(ライブラリやデバッグコード)はreport 関数を、std::printf を使うときの感覚で利用します。

ここで紹介したものは標準出力を委譲するための部品です。使いやすくクラス化するのも良いと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?