gpt4 book ai didi

c++ - 我怎样才能从尾部而不是头部拉出可变参数模板参数?

转载 作者:可可西里 更新时间:2023-11-01 16:36:34 25 4
gpt4 key购买 nike

出于愚蠢的原因,我不会在这里深入,我需要注释掉的行才能工作,而它上面的行不能工作:

template<uint _N, typename... _Args>
struct PartialTuple;

template<uint _N, typename _Arg, typename... _Args>
struct PartialTuple<_N, _Arg, _Args...>: PartialTuple<_N-1, _Args...> {};

template<typename _Arg, typename... _Args>
struct PartialTuple<0, _Arg, _Args...>
{
typedef std::tuple<_Arg, _Args...> type;
};

int main()
{
// I want this to not work...
PartialTuple<1, std::string, std::string, int, int>::type A{"test", 5, 1};

// I want this to work...
//PartialTuple<1, std::string, std::string, int, int>::type B{"test", "test", 5};
}

我尝试将 _Arg_Args... 交换,但无法编译(至少在 GCC 4.6 中):

error: parameter pack argument ‘_Args ...’ must be at the end of the template argument list

我怎样才能从尾部而不是从头部取下元素?

最佳答案

这是一个解决方案:我没有从后面截断 N,而是从前面截断 sizeof...(Args) - N:

#include <tuple>

/* Concatenator helper */

template <typename T, typename Tuple> struct cat;
template <typename T, typename ...Args>
struct cat<T, std::tuple<Args...>>
{
typedef typename std::tuple<T, Args...> value;
};


/* Head-of-tuple */

template <unsigned int, typename...> struct tuple_head;

// Base case. Need to specialize twice, once for one and once for variadic types
template <typename ...Args>
struct tuple_head<0, Args...>
{
typedef std::tuple<> value;
};
template <typename T>
struct tuple_head<0, T>
{
typedef std::tuple<> value;
};

// Recursion step
template <unsigned int N, typename T, typename ...Args>
struct tuple_head<N, T, Args...>
{
typedef typename cat<T, typename tuple_head<N - 1, Args...>::value>::value value;
};


/* User interface */

template <unsigned int N, typename ...Args>
struct PartialTuple
{
typedef typename tuple_head<sizeof...(Args) - N, Args...>::value type;
};


/* Usage */

#include <string>
int main()
{
// I want this to not work...
//PartialTuple<1, std::string, std::string, int, int>::type A{"test", 5, 1};

// I want this to work...
PartialTuple<1, std::string, std::string, int, int>::type B("test", "test", 5);
PartialTuple<0, std::string, std::string, int, int>::type C("test", "test", 5, 6);
}

关于c++ - 我怎样才能从尾部而不是头部拉出可变参数模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6632533/

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