gpt4 book ai didi

c++ - 获取可变参数模板类的第 N 个参数的最简单方法?

转载 作者:IT老高 更新时间:2023-10-28 22:35:26 24 4
gpt4 key购买 nike

我想知道在编译时获取可变参数模板类的第 N 个参数的最简单和更常见的方法是什么(返回值必须是编译器的静态 const为了做一些优化)。这是我的模板类的形式:

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

非常感谢。

编辑:由于 MyClass 将包含 200 多个函数,我无法对其进行专门化。但我可以专门化 MyClass 中的结构或函数。

编辑:从经过验证的答案得出的最终解决方案:

#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 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;
};

关于c++ - 获取可变参数模板类的第 N 个参数的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11811418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com