シンプルな ScopedExit クラスを実装しようとしています。コードは次のとおりです。
#include <iostream>
#include <functional>
template<class R, class... Args>
class ScopedExit
{
public:
ScopedExit(std::function<R(Args...)> exitFunction)
{
exitFunc_ = exitFunction;
}
~ScopedExit()
{
exitFunc_();
}
private:
std::function<R(Args...)> exitFunc_;
};
template<>
class ScopedExit<void>
{
public:
ScopedExit(std::function<void ()> exitFunction)
{
exitFunc_ = exitFunction;
}
~ScopedExit()
{
exitFunc_();
}
private:
std::function<void ()> exitFunc_;
};
void foo()
{
std::cout << "foo() called\n";
}
class Bar
{
public:
void BarExitFunc(int x, int y)
{
std::cout << "BarExitFunc called with x =" << x << "y = " << y << "\n";
}
};
int main()
{
Bar b;
std::cout << "Register scoped exit func\n";
{
ScopedExit<void, int, int> exitGuardInner(std::bind(&Bar::BarExitFunc, &b, 18, 11));
}
ScopedExit exitGuardOutter(foo);
std::cout << "About to exit from the scope\n";
return 0;
}
したがって、いくつかの質問があります。
exit の関数引数をそれに渡す方法は? たとえば、BarExitFunc を 18 と 11 の 2 つの整数引数にバインドします。では、デストラクタで exitFunc_ に渡すにはどうすればよいでしょうか? std::forward<> で関数を呼び出すようなものが必要だと思います。
gcc 4.7.2 (ideone.com から) は、exitGuardOutter について文句を言います。それは言います:
prog.cpp:60:16: エラー: 'exitGuardOutter' の前にテンプレート引数がありません</p>
prog.cpp:60:16: エラー: 予想される ';' 「exitGuardOutter」の前</p>
前もって感謝します。