Indirect forwarding references

后端 未结 1 1274
無奈伤痛
無奈伤痛 2021-01-24 10:09

It is well known that \"direct\" forwarding references works in an easy way :

template
void f(T &&t); // Here we are.

相关标签:
1条回答
  • 2021-01-24 11:04

    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>>{});
    }
    
    0 讨论(0)
提交回复
热议问题