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;
}
"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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With