【发布时间】:2019-06-08 18:38:27
【问题描述】:
我正在尝试使用Template meta-programming 实现一个列表,但没有成功编译下一个代码:
#include <iostream>
template<int Value>
struct Int {
static constexpr int value = Value;
};
template<typename H, typename ...TT>
struct List {
typedef H head;
typedef List<TT...> next; // <-- Too few template arguments for class template 'List'
constexpr static int size = sizeof...(TT) + 1;
};
int main() {
typedef List<Int<1>, Int<2>, Int<3>> list1;
static_assert(list1::head::value == 1, "Failed"); // = Int<1>
static_assert(list1::size == 3, "Failed"); // = 3
typedef typename list1::next list1Tail; // = List<Int<2>, Int<3>>
static_assert(list1Tail::head::value == 2, "Failed");
static_assert(list1Tail::size == 2, "Failed"); // = 2
typedef typename list1Tail::next list2Tail; // = List<Int<3>> <<---error: wrong number of template arguments (0, should be at least 1)
static_assert(list2Tail::head::value == 3, "Failed");
static_assert(list2Tail::size == 1, "Failed");
std::cout << "Passed" << std::endl;
}
出现错误:
In instantiation of ‘struct List<Int<3> >’: error: wrong number of template arguments (0, should be at least 1)
我知道在我的情况下List 必须处理两种类型H 和...TT,但是:
- 为什么调用
List<TT...>还不够? - 我应该如何解决它?
- 在这种情况下编译代码的最佳方法是什么?
【问题讨论】:
-
想想当
TT为空时会发生什么,你有List<TT...>但你至少需要H来定义最少。递归结束时需要专门化。
标签: c++ c++11 variadic-templates template-meta-programming