Reputation: 3824
Here is a code for implementing decorator pattern in C++. It basically accepts a function, and returns a functor. This code works, but I would like to understand why we need the first line (i.e. forward declaration). If this line is removed, I get this compile error: ‘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;
}
};
Upvotes: 2
Views: 228
Reputation: 172964
This is using partial template specialization. The 1st one is the declaration of the primary template, the 2nd one is the partial specialization, for which you have to declare the primary template first.
When you specify the template argument with function type, the specialization version is applied, and it would get the parameter type (i.e. Args...
) and return type (i.e. R
) of the specified function type.
Upvotes: 2