Home  >  Q&A  >  body text

c++ - STL模板部分特例化。

天蓬老师天蓬老师2715 days ago623

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:05:03

    C++ templates are generally used for generics (that is, one code is shared by multiple types), but they can also be used for non-type template parameters, which can be integers, characters, Boolean, etc.Equivalent types can be clearly determined through literals.

    You usually declare a type template parameter as template <typename T>, but here the Non-type template parameter is template <bool B>. This is the only difference. If we want to talk about enable_if this template technique in detail, the key is not in Non-type or partial spec, but in SFINAE. You should learn this aspect.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:05:03

    enable_if says template<bool _test>, so naturally you have to fill in true/false.

    When using it, you will find that if the result of an expression expr is true, then enable_if<expr>::type exists. So you can write code like this:

    template<typename T>
    __forceinline T Copy(typename enable_if<sizeof(T)>=4, T>::type const& t)
    {
        return t;
    }
    

    to test whether a type is no less than 4 bytes. If it is returned as is, a compilation error will occur if it is not.

    reply
    0
  • Cancelreply