Tôi muốn viết một mẫu trả về cho tôi loại số nguyên có chữ ký nhỏ nhất có thể đại diện cho một số đã cho. Đây là giải pháp của tôi:GCC: so sánh luôn đúng do phạm vi hạn chế của kiểu dữ liệu - trong Tham số mẫu?
/**
* Helper for IntTypeThatFits.
* Template parameters indicate whether the given number fits into 8, 16 or 32
* bits. If neither of them is true, it is assumed that it fits 64 bits.
*/
template <bool fits8, bool fits16, bool fits32>
struct IntTypeThatFitsHelper { };
// specializations for picking the right type
// these are all valid combinations of the flags
template<> struct IntTypeThatFitsHelper<true, true, true> { typedef int8_t Result; };
template<> struct IntTypeThatFitsHelper<false, true, true> { typedef int16_t Result; };
template<> struct IntTypeThatFitsHelper<false, false, true> { typedef int32_t Result; };
template<> struct IntTypeThatFitsHelper<false, false, false> { typedef int64_t Result; };
/// Finds the smallest integer type that can represent the given number.
template <int64_t n>
struct IntTypeThatFits
{
typedef typename IntTypeThatFitsHelper<
(n <= numeric_limits<int8_t>::max()) && (n >= numeric_limits<int8_t>::min()),
(n <= numeric_limits<int16_t>::max()) && (n >= numeric_limits<int16_t>::min()),
(n <= numeric_limits<int32_t>::max()) && (n >= numeric_limits<int32_t>::min())
>::Result Result;
};
Tuy nhiên, GCC không chấp nhận mã này. Tôi gặp lỗi "so sánh luôn đúng do phạm vi hạn chế của kiểu dữ liệu [-Werror = type-limits]". Tại sao điều đó lại xảy ra? n là một số nguyên 64 bit đã ký, và tất cả các phép so sánh có thể đúng hoặc sai cho các giá trị khác nhau của n, hoặc tôi có thấy cái gì đó không?
Tôi sẽ rất vui khi được trợ giúp.
Chỉnh sửa: Tôi nên đề cập rằng tôi đang sử dụng C++ 11.
Làm cách nào có thể có _not_ nhỏ hơn 'max' _and_ không quá' phút '? Tôi có đọc sai không? –
@SethCarnegie: Nó đang kiểm tra xem 'n' có nằm trong phạm vi cho ** loại dữ liệu ** khác nhau hay không. –
Đối với những người muốn thử sức với nó, tôi đã quản lý để có được một phiên bản trên [ideone] (http://ideone.com/PhAJN) (không hỗ trợ 'constexpr' nào được nêu ra ...) –