可变参数模板类中需要什么前向声明?

时间:2018-07-04 01:14:55

标签: c++ templates template-specialization

这是用于在C ++中实现装饰器模式的代码。它基本上接受一个函数,并返回一个函子。这段代码有效,但是我想了解为什么我们需要第一行(即前向声明)。如果删除此行,则会出现以下编译错误:‘Decorator’ is not a class template

template <class> class Decorator;

template <class R, class... Args>
class Decorator<R(Args ...)>
{
    std::function<R(Args ...)> f_;
public:
    Decorator(std::function<R(Args ...)> f) : f_(f) {}
    R operator()(Args ... args)
    {
        auto res = f_(args...);
        std::cout << fmt::format("Calling the decorated function with res={}.\n", res);
        return res;
    }
};

1 个答案:

答案 0 :(得分:2)

这正在使用partial template specialization。第一个是主模板的声明,第二个是局部专业化,为此,您必须先声明主模板。

当您使用函数类型指定模板参数时,将应用专业化版本,它将获得指定函数类型的参数类型(即Args...)和返回类型(即R