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

后端 未结 5 1003
没有蜡笔的小新
没有蜡笔的小新 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 03:57

    Starting in c++17 with the introduction of if constexpr you don't even need to provide specializations for this. Unlike a normal if statement the code in the if constexpr will be discarded (not compiled) if the expression is not true. That means you can rewrite your function like

    template
    inline bool f( T n ) 
    {
        if constexpr (std::is_unsigned_v)
            return n <= 100;
        else
            return n >= 0 && n <= 100;
    }   
    

提交回复
热议问题