【问题标题】:Variadic templates with constants带有常量的可变参数模板
【发布时间】:2014-11-17 19:26:24
【问题描述】:

我正在对元编程和可变参数模板进行一些试验,但我遇到了一些令人困惑的行为。我已经将它简化为一个最小的工作示例,但基本上我想跟踪我正在进行多少递归调用。我想通过使第一个模板参数为整数,而第二个模板参数是可变参数列表来做到这一点。最简单的形式如下:

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 定义的行中声明“意外类型'List”。如果没有前面的整数,它可以正常工作。那么有没有办法将可变参数模板与整数模板参数结合起来呢?

【问题讨论】:

  • 对不起@cdhowie,我已经编辑了。
  • next_call 应该在 initial_call 之前
  • next_call 放在initial_call 之前,它是works for me
  • 啊,谢谢@PiotrS。不敢相信我错过了。
  • 看起来它正在将初始化程序解析为 (next_call &lt; 0), List 并在那里中断。

标签: c++ templates visual-studio-2013 variadic-templates


【解决方案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';
}

【讨论】:

  • 太完美了,谢谢!我最终弄清楚了语法错误,这让我很失望,但是有一个完整的例子很好。
猜你喜欢
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2015-12-14
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多