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

标签 c++ templates metaprogramming variadic-templates

我想知道在编译时获取可变参数模板类的第 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/

相关文章:

c++ - gcc 的 asm volatile 是否等同于递归的 gfortran 默认设置?

c++ - 使用类成员函数作为比较器调用 std::equal 时出错

c++ - QT部署错误

c++ - 这个模板语法可以改进吗?

compilation - 在编译字中编译匿名字

ruby-on-rails - 如何在模块中为类方法起别名?

c++ - 难以创建 vulkan 实例

c++ - 使用模板应用功能模板

c++ - 按通用引用返回

C++模板元编程成员函数循环展开