Indirect forwarding references

女生的网名这么多〃 提交于 2019-12-20 04:28:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!