私はいくつかのライブラリ関数を構築しています。そのうちの 1 つは、基本的に任意のキーを持つタイマー クラスです。概念的には次のようになります。
template <typename Key>
class Timer
{
void tic(Key key) {tics[key] = std::clock();
void toc(Key key)
{
// calling this before tic has been called is fine
if (!tic.find(key))
tocs[key] = 0;
else
tocs[key] = std::clock() - tics[key];
// BUT: writing code that calls "tocs" without ever calling "tics" should trigger
// a compile-time error! How do I do this? Is it possible?
}
private:
std::map<Key,clock_t> tics;
std::map<Key,clock_t> tocs;
}
このクラスのタスクは、各キーの呼び出しtic
と呼び出しの間の時間を測定することだけです。たとえば、クラスが関数呼び出し間の時間を測定できるようにするために、前にtoc
呼び出すことは完全に合法である必要があります。ただし、コードの他の部分で対応する toc/tic を指定せずに aまたは aを呼び出すのは意味がないため、明らかにコーディング エラーです。コンパイル時に報告したいと思います。toc
tic
tic
toc
したがって、これで問題ありません。
Timer<int> timer;
while (1)
{
timer.toc(0);
// this reports the time elapses between the while
// loop ending and the while loop starting
timer.tic(1);
}
ただし、これらはコンパイル時エラーを生成する必要があります (まあ、警告の方が適しています)。
Timer<int> timer;
while (1)
{
timer.toc(1); // this will always return 0
timer.tic(0); // this is an unused initialization
}
これを達成することは可能ですか?答えは「いいえ」だと思いますが、確認したかったのです。