Given:
template<typename T> inline bool f( T n ) { return n >= 0 && n <= 100; }
When used with an unsigned
type generates a warning:
unsigned n; f( n ); // warning: comparison n >= 0 is always true
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:
template<typename T> inline bool f( unsigned T n ) { return n <= 100; }
but gcc 4.2.1 doesn't like that. (I didn't think that kind of partial template specialization would be legal anyway.)
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type.
You can use enable_if
with the is_unsigned
type trait:
template <typename T> typename std::enable_if<std::is_unsigned<T>::value, bool>::type f(T n) { return n <= 100; } template <typename T> typename std::enable_if<!std::is_unsigned<T>::value, bool>::type f(T n) { return n >= 0 && n <= 100; }
You can find enable_if
and is_unsigned
in the std
or std::tr1
namespaces if your compiler supports C++0x or TR1, respectively. Otherwise, Boost has an implementation of the type traits library, Boost.TypeTraits. The boost implementation of enable_if
is a little different; boost::enable_if_c
is similar to the TR1 and C++0x enable_if
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With