间接转发参考 [英] Indirect forwarding references

查看:70
本文介绍了间接转发参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,直接转发引用的工作方式很简单:

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?

推荐答案

否,这是不可能的。如果要限制该函数只接受 some_class_template ,则必须使用类型特征:

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
{};

特征可以以多种方式使用。一个是SFINAE:

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>>{});
}

这篇关于间接转发参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆