获得可变参数模板类的第N个参数的最简单方法? [英] Easiest way to get the N-th argument of a variadic templated class?
问题描述
我想知道在编译时获取可变参数模板化类的第N个参数的最简单,更常见的方法是什么(返回值必须作为编译器的静态const为了做一些优化).这是我的模板化类的形式:
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 ?
};
非常感谢您.
由于MyClass将包含200多个函数,因此我无法对其进行专门化.但是我可以在MyClass内专门化一个结构或函数.
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;
}
推荐答案
这是另一种方法:
template<unsigned int index, unsigned int In, unsigned int... remPack> struct getVal
{
static const unsigned int val = getVal<index-1, remPack...>::val;
};
template<unsigned int In, unsigned int...remPack> struct getVal<0,In,remPack...>
{
static const unsigned int val = In;
};
template<unsigned int... T> struct MyClass
{
//go to any arg by : getVal<Some_Unsigned_Index, T...>::val;
};
测试: http://liveworkspace.org/code/4a1a9ed4edcf931373e7ab0bf098c847
,如果您因无法将'T ...'扩展到固定长度的参数列表中"而受到打击,则 http://ideone.com/YF4UJ
and if you get sting by "cannot expand 'T...' into a fixed-length argument list" http://ideone.com/YF4UJ
这篇关于获得可变参数模板类的第N个参数的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!