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

后端 未结 5 1005
没有蜡笔的小新
没有蜡笔的小新 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 take advantage of the wrap-around behavior of unsigned integers.

    template struct bool_ { };
    
    template
    inline bool f( T n, bool_ ) {
      return n >= 0 && n <= 100;
    }
    
    template
    inline bool f( T n, bool_ ) {
      return n <= 100;
    }
    
    template
    inline bool f( T n ) {
      return f(n, bool_<(static_cast(-1) > 0)>());
    }   
    

    It's important not to say >= 0, to avoid a warning again. The following appears to trick GCC too

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

提交回复
热议问题