Re: Portable list of unsigned integer types
On 13/10/09 14:17, Francesco S. Carta wrote:
[]
To avoid the weird part of my suggestion (duplicating the code in the
template body) one could make two different templates and wrap the
decision in a third one:
-------
#include<limits>
template<class T> void signed_algo(const T& one, const T& two) {
// ...
}
template<class T> void unsigned_algo(const T& one, const T& two) {
// ...
}
template<class T> void algo(const T& one, const T& two) {
if(std::numeric_limits<T>::is_signed) {
signed_algo(one, two);
} else {
unsigned_algo(one, two);
}
}
-------
Well, you surely have considered all of this already, I'm posting it
just for the occasional reader.
An occasional reader is here ;)
Noticed that algo() uses a runtime if() statement which causes both
signed_algo and unsigned_algo to be instantiated for every T. The
optimizer will determine that std::numeric_limits<T>::is_signed is a
compile-time constant and throw away the dead branch, but still both
templates are instantiated.
It is easy to eliminate the unnecessary instantiation and make the
compiler instantiate only the template function which is actually called:
#include <limits>
template<bool> struct Bool {};
typedef Bool<true> True;
typedef Bool<false> False;
template<class T>
void algo(const T& one, const T& two, /*signed*/ True) {
// ...
}
template<class T>
void algo(const T& one, const T& two, /*signed*/ False) {
// ...
}
template<class T> void algo(const T& one, const T& two) {
algo(one, two, Bool<std::numeric_limits<T>::is_signed>());
}
int main()
{
algo(1, 1);
algo(1u, 1u);
}
--
Max