Partial template specialization based on “signed-ness” of integer type?

后端 未结 5 1004
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 03:37

Given:

template
inline bool f( T n ) {
  return n >= 0 && n <= 100;
}   

When used with an unsigned

5条回答
  •  遥遥无期
    2020-12-09 04:15

    You can use enable_if with the is_unsigned type trait:

    template 
    typename std::enable_if::value, bool>::type f(T n)
    {
        return n <= 100;  
    }
    
    template 
    typename std::enable_if::value, bool>::type f(T n)
    {
        return n >= 0 && n <= 100;  
    }
    

    You can find enable_if and is_unsigned in the std or std::tr1 namespaces if your compiler supports C++0x or TR1, respectively. Otherwise, Boost has an implementation of the type traits library, Boost.TypeTraits. The boost implementation of enable_if is a little different; boost::enable_if_c is similar to the TR1 and C++0x enable_if.

提交回复
热议问题