テンプレートコールバックパラメータを使用するときに特定のコールバックシグネチャを適用したいと考えています。テンプレートコールバックパラメータに特定のシグネチャを適用する方法
- メソッドがコールバックを受け入れる深くではなく、ユーザー呼び出しサイトでコンパイルエラーを取得します。
- 少なくとも驚きの原則を守り、コールバックを使用して実装がなど(正確な署名の試合を)その値をチェックしません値を返すコールバックを提供するからユーザーを防ぐ
- 利用慣用的なC++と可能な限りのベストプラクティス。効率化してください。 C#の出身
は、私が最初にそうようなアクションとのFuncクラスを模倣しようとした:
template<typename ...TArgs> using Action = std::function<void(TArgs...)>;
template<typename TRet, typename ...TArgs> using Func = std::function<TRet(TArgs...)>;
それは私がこれを避けるために聞いたのstd ::関数を使用除いこれは、[OK]を作品'単純な'タスク(失敗#3)。また、残念ながら上記の#2の要件を満たしていません。
void DoActionStuff(Action<int, float> callback)
{
callback(1, 2.0);
}
void DoFuncStuff(Func<float, int, float> callback)
{
float result = callback(1, 2.0);
if (result > 100.0) { throw runtime_error("derp"); };
}
DoActionStuff([](int x, float y) { cout << x << " " << y << endl; }); // OK
DoActionStuff([](int x, float y) { cout << x << " " << y << endl; return x * y; }); // No error :(Why not?
DoFuncStuff([](int x, float y) { cout << x << " " << y << endl; }); // OK - We get a compiler error right here at the call-site for this one...
DoFuncStuff([](int x, float y) { cout << x << " " << y << endl; return x * y; }); // OK
3つの要件をすべて満たすにはどうすればよいですか?どのタイプのコールバックが必要なのかを正確に伝達するために、このメソッドに優れたシグネチャを提供するために使用できる、素晴らしい、特色のあるマジックがありますか?
template<typename TCallback>
void DoStuff(TCallback callback) { ... } // Unnecessarily burdens the client of this api (they have no idea the signature to use here)
DoActionStuff([i](auto f、auto f){cout << i + f;}) 'を実行したい場合はどうすればよいですか?あなたはそれを禁止したいですか? – Barry