tags:

views:

718

answers:

6

Is there an elegant way to specialize a template based on one of its template parameters?

Ie.

template<int N> struct Junk {
    static int foo() {
        // stuff
        return Junk<N - 1>::foo();
    }
};

// compile error: template argument '(size * 5)' involves template parameter(s)
template<int N> struct Junk<N*5> {
    static int foo() {
        // stuff
        return N;
    }
};

template<> struct Junk<0> {
    static int foo() {
        // stuff
        return 0;
    }
};

Ie. I am trying to specialize a template based on the parameter being divisible by 5. The only way I can seem to do it is like below:

template<int N> struct JunkDivisibleBy5 {
    static int foo() {
        // stuff
        return N;
    }
};

template<int N> struct Junk {
    static int foo() {
        // stuff
        if ((N - 1) % 5 == 0 && N != 1)
            return JunkDivisibleBy5<N - 1>::foo();
        else
            return Junk<N - 1>::foo();
    }
};


template<> struct Junk<0> {
    static int foo() {
        // stuff
        return 0;
    }
};

But this is significantly less elegant, and also necessitates instantiation of all templates even if the template argument shouldn't require it.

+11  A: 

How's this:

#include <iostream>
using namespace std;

template < typename T, T N, T D >
struct fraction {
    typedef T value_type;
    static const value_type num = N;
    static const value_type denom = D;
    static const bool is_div = (num % denom == 0);
};

template< typename T, T N, T D, bool P >
struct do_if {
    static void op() { cout << N << " NOT divisible by " << D << endl; }
};

template< typename T, T N, T D >
struct do_if< T, N, D, true > {
    static void op() { cout << N << " divisible by " << D << endl; }
};

template < int N >
void foo() {
    typedef fraction< int, N, 5 > f;
    do_if< typename f::value_type, f::num, f::denom, f::is_div >::op();
}

int main() {
    foo< -5 >();
    foo< -1 >();
    foo< 0 >();
    foo< 1 >();
    foo< 5 >();
    foo< 10000005 >();
    return 0;
}
jwfearn
have you tried to compile this?
David Nehme
It compile fine, what's wrong?
KTC
I compiled it, ran it and verified the test results. I included the entire program so others can do the same.
jwfearn
not with g++ 4.1.3meta_programming.cpp:10: error: explicit specialization in non-namespace scope struct my<N>meta_programming.cpp:10: error: enclosing class templates are not explicitly specialized
David Nehme
CLARIFICATION: I compiled it with Visual C++ 2008, ran it and verified the test results.
jwfearn
Sorry @David Nehme, I don't use g++. If you have a g++ compatible solution, please post it because I'd like to learn more about what I'm doing wrong.
jwfearn
I re-worked this to (hopefully) be more acceptable to g++. It still works fine with VC9. @David Nehme, can you report success/failure on g++?
jwfearn
I tried w/ g++ 4.3.3: no dice :(~$ g++ metaprog.cpp -o metaprogmetaprog.cpp: In function ‘void foo()’:metaprog.cpp:25: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T, T N, T D, bool P> struct do_if’metaprog.cpp:25: error: expected a type, got ‘f::value_type’metaprog.cpp:25: error: ‘<type error>’ is not a valid type for a template constant parametermetaprog.cpp:25: error: ‘<type error>’ is not a valid type for a template constant parametermetaprog.cpp:25: error: invalid type in declaration before ‘;’ token
Matt J
put typename before f::value_type. f::value_type is a dependent type.
Johannes Schaub - litb
@MattJ, I edited as per @litb's suggestion (I also shortened 'numerator' to 'num' and 'denominator' to 'denom' to avoid a horizontal scrollbar). Does this help?
jwfearn
Works like a charm :)
Matt J
A: 

I would hardly call it elegant, but here's my version of your code using only templates for computation (along with a test thing) --

#include <iostream>

template < int N > struct JunkDivBy5 {
    static int foo() {
     return N;
    }
};

template < int N > struct Junk {
    template < int N1 > struct _JunkCond {
     enum { val = ( N1 != 1 && ( N1 - 1 ) % 5 == 0 ) ? 1 : 0 };
    };

    template < int M, int N1 > struct _JunkBranch { /* Error */ };

    template < int N1 > struct _JunkBranch< 1, N1 > {
     typedef JunkDivBy5< N1 - 1 > Type;
    };

    template < int N1 > struct _JunkBranch< 0, N1 > {
     typedef Junk< N1 - 1 > Type;
    };

    static int foo() {
     return _JunkBranch< _JunkCond< N >::val, N >::Type::foo();
    }
};

template <> struct Junk< 0 > {
    static int foo() {
     return 0;
    }
};

int main( int argc, char *argv[] ) {
    std::cout << Junk< 0 >::foo() << std::endl;
    std::cout << Junk< 5 >::foo() << std::endl;
    std::cout << Junk< 7 >::foo() << std::endl;
    std::cout << Junk< 25 >::foo() << std::endl;
}
hark
+4  A: 

All calculations could be made in compile-time:

#include <iostream>

template<int N> struct Junk {
    enum { IsDivisibleBy5 = (N % 5 == 0) };
    template<bool D> struct JunkInternal {
        enum { Result = Junk<N-1>::Result };
    };
    template<> struct JunkInternal<true> {
        enum { Result = N };
    };
    enum { Result = JunkInternal<IsDivisibleBy5>::Result };
};

int main(int, char**)
{
    std::cout << Junk< 0 >::Result << std::endl;
    std::cout << Junk< 7 >::Result << std::endl;
    std::cout << Junk< 10 >::Result << std::endl;

    return 0;
}
Igor Semenov
+2  A: 

Inheritance works quite well:

template<int N> struct Junk : private JunkBase < N % 5 > { };

template<int N> struct JunkBase {
    static int foo() {
        // stuff
        return Junk<N - 1>::foo();
    }
};
template< > struct JunkBase<0> {
    static int foo() {
        return 0;
    }
};

You might need to pass N to JunkBase::foo, if you need N/5 too.

MSalters
+3  A: 

Code

template<int A, bool = !(A % 5)>
struct select : select<A-1> { };

template<int A>
struct select<A, true> { static int const value = A; };

template<>
struct select<0, true> { static int const value = 0; };

int main() {
    std::cout << select<1>::value; // 0
    std::cout << select<7>::value; // 5
    std::cout << select<10>::value; // 10
}

Keep the divisor variable

template<int A, int D, bool = !(A % D)>
struct select : select<A-1, D> { };

template<int A, int D>
struct select<A, D, true> { static int const value = A; };

template<int D>
struct select<0, D, true> { static int const value = 0; };

int main() {
    std::cout << select<1, 3>::value; // 0
    std::cout << select<7, 3>::value; // 6
    std::cout << select<10, 3>::value; // 9
}
Johannes Schaub - litb
+4  A: 

Using D programming language templates, one could write it as:

struct Junk(int N)
{
    static int foo()
    {
        static if (N == 0)
            return 0;
        else static if ((N % 5) == 0)
            return N;
        else
            return Junk!(N - 1).foo();
    }
}

static if's are executed at compile time.

Walter Bright