如何摆脱手动类模板参数规范

How to get rid of the manual class template parameter specification

本文关键字:参数 何摆脱      更新时间:2023-10-16

还有比这更通用的方法来编写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; });

可能吗?

在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 x = at_scope_exit([]() { std::cout << "Hello world" << std::endl; });