Voglio scrivere un modello che mi restituisce il più piccolo tipo intero con segno che può rappresentare un dato numero. Questa è la mia soluzione:GCC: il confronto è sempre vero a causa della gamma limitata di tipi di dati - in Parametro modello?
/**
* 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;
};
Tuttavia, GCC non accetta questo codice. Ricevo un errore "il confronto è sempre vero a causa della gamma limitata di tipi di dati [-Werror = type-limits]". Perché succede? n è un intero con segno a 64 bit e tutti i confronti possono essere vere o false per diversi valori di n o sto trascurando qualcosa?
Sarò felice per qualsiasi aiuto.
Edit: Devo dire che sto usando C++ 11.
Come potrebbe essere qualcosa _not_ meno di 'max' _e_ non più di' min'? Sto leggendo quello sbagliato? –
@SethCarnegie: Controlla se 'n' rientra negli intervalli per ** diversi ** tipi di dati. –
Per coloro che vogliono cimentarsi in questo, sono riuscito a ottenere una versione su [ideone] (http://ideone.com/PhAJN) (che non supporta 'constexpr' ancora ...) –