Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.)

like image 293
Paul J. Lucas Avatar asked Jan 21 '11 17:01

Paul J. Lucas


People also ask

What is meant by template specialization in C++?

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.

What is the specialty of a template function give example?

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.


1 Answers

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.

like image 144
James McNellis Avatar answered Sep 21 '22 06:09

James McNellis