Re: Portable list of unsigned integer types
On Oct 13, 12:31 pm, "Fred Zwarts" <F.Zwa...@KVI.nl> wrote:
Kai-Uwe Bux wrote:
Fred Zwarts wrote:
I have created a template function for a generic algorithm. For
unsigned integer types, a small modification in the algorithm is
needed, because I can't use negative values there. So, I want to
make specializations for all unsigned integer types.
Maybe the following helps:
template < typename T >
struct is_signed {
static bool const value = 0 > T(-1);
};
I assume that it is not possible in C++ to write one specialization
for all unsigned integer type, but that a specialization for each
unsigned integer type must be created.
No, but you could do:
template < typename T, bool IsSigned = is_signed<T>::value >
struct ...
and partially specialize that for <T,true> and <T,false>.
[...]
I tried something along these lines, but it turned out to my surprise,
that partial specializations are not allowed for template functions,
only for template classes/structs. Of course I could encapsulate the
function in a class and add a wrapper function...
Or you could forward to an overloaded function, something like:
template< bool > class Discrim {};
template< typename T >
void helper( T value, Discrim< false > )
{
// signed...
}
template< typename T >
void helper( T value, Discrim< true > )
{
// unsigned...
}
template< typename T >
void function( T value )
{
helper( value, Discrim< is_signed< T >::value >() ) ;
}
If you're doing a lot of this (or even more than once), you'll have
Discrim already written, and maybe even is_signed, so all that's left
is
the two overloads. (I don't claim that this is a better or a worse
solution than the partial specializations suggested by Kai-Uwe---I
generally use his method myself. But it's an alternative you might
consider.)
--
James Kanze