无法使用模板理解函数定义

时间:2017-08-11 01:49:11

标签: c++ templates

我知道如何在C ++中使用模板,但无法理解下面的代码,尤其是最后一行。它是半精度类型的运算符*重载。有人可以向我解释一下吗? (这里detail是名称空间)

    /// SFINAE helper for generic half-precision functions.
    /// This class template has to be specialized for each valid combination of argument types to provide a corresponding
    /// `type` member equivalent to \a T.
    /// \tparam T type to return
    template<typename T,typename,typename=void,typename=void> struct enable {};
    template<typename T> struct enable<T,half,void,void> { typedef T type; };
    template<typename T> struct enable<T,expr,void,void> { typedef T type; };
    template<typename T> struct enable<T,half,half,void> { typedef T type; };
    template<typename T> struct enable<T,half,expr,void> { typedef T type; };
    template<typename T> struct enable<T,expr,half,void> { typedef T type; };
    template<typename T> struct enable<T,expr,expr,void> { typedef T type; };
    template<typename T> struct enable<T,half,half,half> { typedef T type; };
    template<typename T> struct enable<T,half,half,expr> { typedef T type; };
    template<typename T> struct enable<T,half,expr,half> { typedef T type; };
    template<typename T> struct enable<T,half,expr,expr> { typedef T type; };
    template<typename T> struct enable<T,expr,half,half> { typedef T type; };
    template<typename T> struct enable<T,expr,half,expr> { typedef T type; };
    template<typename T> struct enable<T,expr,expr,half> { typedef T type; };
    template<typename T> struct enable<T,expr,expr,expr> { typedef T type; };

.... some codes ...   

template<typename T> typename detail::enable<half&,T>::type operator*=(T rhs) { return *this *= static_cast<float>(rhs); }

我知道不同的模板对有不同类型的struct enable。但结构启用声明在上面做了什么?它是否在结构中定义了一个类型?(因此type在sturct中有类型T?)并且在模板说明符中,例如是什么意思?我不知道这里的expr是什么。它是一种类型还是具有特殊含义?

1 个答案:

答案 0 :(得分:1)

据我所知,对于此特定的 operator*=只有前3行发挥了作用:

template<typename T,typename,typename=void,typename=void> struct enable {};
template<typename T> struct enable<T,half,void,void> { typedef T type; };
template<typename T> struct enable<T,expr,void,void> { typedef T type; };

此外,您可以更简单地重写它并获得相同的结果:

template<typename T,typename> struct enable {};
template<typename T> struct enable<T,half> { typedef T type; };
template<typename T> struct enable<T,expr> { typedef T type; };

运营商定义的含义不会改变:

template<typename T> typename detail::enable<half&,T>::type operator*=(T rhs) { return *this *= static_cast<float>(rhs); }

在编译时转换为这两个中的一个:

half& operator*=(half rhs) { return *this *= static_cast<float>(rhs); }
half& operator*=(expr rhs) { return *this *= static_cast<float>(rhs); }

人为限制您使用halfexpr作为参数类型。

其他struct enable模板专精在其他地方使用,但不适用于此特定运营商。

相关问题