还有比这更通用的编写Finalizer类的方法吗?
#include <functional>
#include <iostream>
template <typename T>
class Finalizer
{
public:
Finalizer(const std::function<T>& f) : _f(f) {}
~Finalizer()
{
_f();
}
private:
std::function<T> _f;
};
int main()
{
Finalizer<void()> finalizer([]() { std::cout << "str" << std::endl; });
}我希望摆脱手动类模板参数规范,以便能够编写如下代码:
Finalizer finalizer([]() { std::cout << "str" << std::endl; });有可能吗?
发布于 2016-03-10 10:02:35
在C++中,类型推断仅适用于函数模板,而不适用于类模板。您需要一个make_finalizer函数来执行模板参数推导。
另外,您根本不需要使用std::function,不需要支付运行时成本,除非您确实希望它被类型擦除。
template <typename F>
class Finalizer
{
public:
Finalizer(const F & c) : f_(c) {}
Finalizer(F && c) : f_(std::move(c)) {}
Finalizer(const Finalizer &) = delete;
Finalizer(Finalizer && other) :
valid_(other.valid),
f_(std::move(other.f_))
{
other.valid_ = false;
}
Finalizer& operator=(const Finalizer &) = delete;
Finalizer& operator=(Finalizer && other)
{
Finalizer tmp(std::move(other));
swap(tmp);
return *this;
}
~Finalizer()
{
if ( valid_ )
f_();
}
void swap(Finalizer & other) noexcept
{
using std::swap;
swap(other.valid_, valid_);
swap(other.f_, f_);
}
private:
bool valid_ = true;
F f_;
};
template<class F>
Finalizer< std::remove_reference_t<F> > at_scope_exit(F && x)
{
return Finalizer< std::remove_reference_t<F> >(std::forward<F>(x));
}并与auto一起使用:
auto x = at_scope_exit([]() { std::cout << "Hello world" << std::endl; });https://stackoverflow.com/questions/35912747
复制相似问题