我正在尝试使用元编程和可变参数模板,而且我遇到了一些令人困惑的行为问题。我已将其剥离到最低限度的工作示例,但基本上我想跟踪我正在进行的递归调用次数。我想通过使第一个模板参数为整数来实现此目的,而第二个模板参数是可变参数列表。最简单的形式看起来像这样:
template<typename... List>
struct initial_call{
static const int val = next_call<0, List...>::val;
};
template<int D, typename... List>
struct next_call {
static const int val = D;
};
所以忽略了这个代码毫无意义的事实,它并没有在VS2013上编译,在initial_call定义内的行内声称&#34;意外类型&#39; List&#34;。如果没有前面的整数,它可以正常工作。那么有没有办法将可变参数模板与整数模板参数结合起来?
答案 0 :(得分:1)
你可能想要这样的东西(计算类型的数量):
#include <iostream>
// More than one type: Increment size and consume.
template<size_t N, typename T, typename... List>
struct calculate_list_size {
static const size_t value = calculate_list_size<N + 1, List...>::value;
};
// Last type: Increment size and terminate.
template<size_t N, typename T>
struct calculate_list_size<N, T> {
static const size_t value = N + 1;
};
// Forward to calculate_list_size.
template<typename... List>
struct list_size {
static const size_t value = calculate_list_size<0, List...>::value;
};
// Empty list
template<>
struct list_size<> {
static const size_t value = 0;
};
int main()
{
std::cout << list_size<char, short, int>::value << '\n';
std::cout << list_size<>::value << '\n';
}