Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to get the N-th argument of a variadic templated class?

I wonder what is the easiest and more common way to get the N-th parameter of a variadic templated class at compile-time (The returned value has to be as a static const for the compiler in order to do some optimizations). Here is the form of my templated class :

template<unsigned int... T> MyClass
{
    // Compile-time function to get the N-th value of the variadic template ?
};

Thank you very much.

EDIT : As MyClass will contain more than 200 functions, I can't specialize it. But I can specialize a struct or a function inside MyClass.

EDIT : Final solution derived from the validated answer :

#include <iostream>

template<unsigned int... TN> class MyClass
{
    // Helper
    template<unsigned int index, unsigned int... remPack> struct getVal;
    template<unsigned int index, unsigned int In, unsigned int... remPack> struct getVal<index, In,remPack...>
    {
        static const unsigned int val = getVal<index-1, remPack...>::val;
    };
    template<unsigned int In, unsigned int...remPack> struct getVal<1,In,remPack...>
    {
        static const unsigned int val = In;
    };

    // Compile-time validation test
    public:
        template<unsigned int T> inline void f() {std::cout<<"Hello, my value is "<<T<<std::endl;}
        inline void ftest() {f<getVal<4,TN...>::val>();} // <- If this compile, all is OK at compile-time
};
int main()
{
    MyClass<10, 11, 12, 13, 14> x;
    x.ftest();
    return 0;
}
like image 468
Vincent Avatar asked Aug 04 '12 19:08

Vincent


1 Answers

"Design by induction" should come out something like this:

template<unsigned int N, unsigned int Head, unsigned int... Tail>
struct GetNthTemplateArgument : GetNthTemplateArgument<N-1,Tail...>
{
};


template<unsigned int Head, unsigned int... Tail>
struct GetNthTemplateArgument<0,Head,Tail...>
{
    static const unsigned int value = Head;
};

template<unsigned int... T> 
class MyClass
{
     static const unsigned int fifth = GetNthTemplateArgument<4,T...>::value;
};
like image 50
Ben Voigt Avatar answered Oct 21 '22 06:10

Ben Voigt