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

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

    Is there any clever way not to do the comparison n >= 0 when T is an unsigned type? I tried adding a partial template specialization:

    The optimizer should drop the code for the compare since it detected the condition.

    For Clang, add -Wno-tautological-compare to squash the warning. For GCC/G++, add -Wno-type-limits to squash the warning.

    If you are using a compiler that support pragma diagnostic {push|pop} you can:

    #if (GCC_VERSION >= 40600) || (LLVM_CLANG_VERSION >= 10700) || (APPLE_CLANG_VERSION >= 20000)
    # define GCC_DIAGNOSTIC_AVAILABLE 1
    #endif    
    
    #if MSC_VERSION
    # pragma warning(push)
    # pragma warning(disable: 4389)
    #endif
    
    #if GCC_DIAGNOSTIC_AVAILABLE
    # pragma GCC diagnostic push
    # pragma GCC diagnostic ignored "-Wsign-compare"
    # if (LLVM_CLANG_VERSION >= 20800) || (APPLE_CLANG_VERSION >= 30000)
    #  pragma GCC diagnostic ignored "-Wtautological-compare"
    # elif (GCC_VERSION >= 40300)
    #  pragma GCC diagnostic ignored "-Wtype-limits"
    # endif
    #endif
    
    template
    inline bool f( T n ) {
      return n >= 0 && n <= 100;
    }
    
    #if GCC_DIAGNOSTIC_AVAILABLE
    # pragma GCC diagnostic pop
    #endif
    
    #if MSC_VERSION
    # pragma warning(pop)
    #endif
    

    Also see Comparison is always false due to limited range…

提交回复
热议问题