问题
It is well known that "direct" forwarding references works in an easy way :
template<typename T>
void f(T &&t); // Here we are.
Now, how to use forwarding references in an indirect way :
template<typename T>
void f(some_class_template<T> &&f); // Here it is an rvalue reference and not universal one
Is there a way to have a forwarding reference in this second case?
回答1:
No, this is not possible. If you want to constrain the function to only accept some_class_template, you have to use a type trait:
template <typename T>
struct is_some_class_template
: std::false_type
{};
template <typename T>
struct is_some_class_template<some_class_template<T>>
: std::true_type
{};
The trait can be used in several ways. One is with SFINAE:
template <typename T,
std::enable_if_t<is_some_class_template<std::decay_t<T>>::value, int> = 0>
void f(T&& f); // f is some_class_template<U> for some U
Or you may find tag dispatch to be preferable:
template <typename T>
void f_impl(T&& f, std::true_type); // f is some_class_template<U> for some U
template <typename T>
void f_impl(T&& f, std::false_type); // f is something else
template <typename T>
void f(T&& f) {
return f_impl(std::forward<T>(f), is_some_class_template<std::decay_t<T>>{});
}
来源:https://stackoverflow.com/questions/49244948/indirect-forwarding-references