mardi 10 mars 2015

Checking for negatives in template?

This isn't a very important problem, but it's something that has been bugging me for a while now. Basically, I've taken up to learning metaprogramming using templates in C++ simply because it seems interesting. In learning I found the simple factorial example:



template <int n>
struct factorial {
enum { value = factorial<n - 1>::value };
};

template <>
struct factorial<0> {
enum { value = 1 };
};


From this I wanted to add my own portion taken from an extremely basic program assignment from an introduction course a friend of mine is taking. The only additional part I need to add is to print -1 if the number given is negative.


This is where I'm having trouble. I've tried several different things, but it quickly gets out of hand and the errors are very confusing most of the time. At this point I'm wondering if it's possible to do something like this simply. At first I thought it would be as easy as this:



template <int n>
struct factorial {
enum { value = (n < 0) ? -1 : factorial<n>::value };
};

template <>
struct factorial<0> {
enum { value = 1 };
};


But this runs in the compiler until it quits when given a negative number. I've also tried several different things involving making 2-6 more functions and temporary typedefs and other things and it becomes a large mess of errors.


So to make this short: Is there a way to conditionally execute another template if the number given is negative? For example, something like this:



template <int n>
struct factorial {
enum { value = factorial<n, negative<n>::value>::value };
};

template <>
struct factorial<0> {
enum { value = 1 };
};

template <>
struct factorial<(n < 0)> {
enum { value = -1 };
};

Aucun commentaire:

Enregistrer un commentaire