Re: Specializing Perfect Forwarding Templates?
On 16 Mrz., 06:22, Scott Meyers wrote:
Function templates can be partially or fully specialized,
Can they be? partially specialized? If so, this would be a new C++0x
feature. I take your word for it.
but is it
possible to specialize templates that perform perfect forwarding?
The code you provided does not contain a partial specialization of a
function template. You *overloaded* the function template fwd with
another "more specialized" one. That's different.
void f(std::string*&)
{
std::cout << "f(lref)\n";
}
void f(const std::string*&)
{
std::cout << "f(const lref)\n";
}
void f(std::string*&&)
{
std::cout << "f(rref)\n";
}
template<typename T>
void fwd(T&& param)
{
std::cout << "General forwarding template => ";
f(std::forward<T>(param));
}
template<typename T>
void fwd(T*&& param)
{
std::cout << "T*&& forwarding template => ";
f(std::forward<T*>(param));
}
From your use of std::forward I gather that you expect this template
to catch pointer lvalues and rvalues. But the deduction rule that
makes perfect forwarding possible is restricted to a function
parameter pattern "T&&" where T is a template parameter. Perfect
forwarding not only relies on the deduction rules but also on
reference collapsing. So, to make T&& an lvalue reference we just set
T to be an lvalue reference (or let the compiler deduce it to be an
lvalue reference). Reference collapsing makes T&& with T=U& into
T&&=U&. But T*&& can *never* be an lvalue reference regardless of what
T is. T*&& is *always* an rvalue reference.
SG