可变参数模板 class 中需要的前向声明是什么?
What is this forward declaration needed in a variadic template class?
这是一段用C++实现装饰器模式的代码。它基本上接受一个函数,returns 一个仿函数。这段代码有效,但我想了解为什么我们需要第一行(即前向声明)。如果删除此行,我会收到此编译错误:‘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;
}
};
这正在使用 partial template specialization。第一个是主模板的声明,第二个是部分特化,你必须先声明主模板。
当你用函数类型指定模板参数时,应用特化版本,它会得到参数类型(即Args...
)和return类型(即R
) 指定的函数类型。
这是一段用C++实现装饰器模式的代码。它基本上接受一个函数,returns 一个仿函数。这段代码有效,但我想了解为什么我们需要第一行(即前向声明)。如果删除此行,我会收到此编译错误:‘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;
}
};
这正在使用 partial template specialization。第一个是主模板的声明,第二个是部分特化,你必须先声明主模板。
当你用函数类型指定模板参数时,应用特化版本,它会得到参数类型(即Args...
)和return类型(即R
) 指定的函数类型。