我正在尝试实现简单的 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;
}
所以,有几个问题:
如何将出口的函数参数传递给它?例如,我用两个整数参数绑定 BarExitFunc:18 和 11。那么如何将它传递给析构函数中的 exitFunc_ 呢?我想我需要使用 std::forward<> 之类的调用函数。
gcc 4.7.2(来自 ideone.com)抱怨 exitGuardOutter。它说:
prog.cpp:60:16: 错误:在“exitGuardOutter”之前缺少模板参数</p>
prog.cpp:60:16: 错误: 预期 ';' 在'exitGuardOutter'之前</p>
提前致谢。