Specialize pattern based on positivity of argument

Given the pattern

template <int n>
void f(){...};

I know that I can specialize it for certain values nby doing:

template <>
void f<2>(){...};

But is there a method that allows me to specialize it for all the positive n?

I thought of the following:

template <int n>
void f<n>(){
    int dummy[n]; //invalid for n < 0
    ...
};

So, for n<0this code is not valid, and the compiler will apply the previous definition. Unfortunately, all I get is a mistake redefinition of 'void f<n>()'.

Note. I assume this is probably not supported by the standard. I ask if there is any method (possibly metaprogramming a template) to achieve this effect.

+5
source share
1 answer

- . , : n bool, , n , , n . , f .

:

template <int n, bool isNegative> struct fImpl {
    static void f() {
       /* ... code for when n is positive ... */
    }
};
template <int n> struct fImpl<n, true> {
    static void f() {
       /* ... code for when n is negative ... */
    }
};

template <int n> void f() {
    fImpl<n, (n < 0)>::f();
}

SFINAE std::enable_if ++ 11 ( Boost);

template <int n> void f(typename std::enable_if<(n < 0)>::type* = 0) {
    /* ... n is negative ... */
}

template <int n> void f(typename std::enable_if<(n >= 0)>::type* = 0) {
    /* ... n is positive ... */
}

, n , .

, !

+13

All Articles