abe*_*nky 1 c++ templates variadic-templates
我是第一次尝试变量模板元编程,并且始终遇到我无法追踪的编译器错误.
我正在关注此页面上的"元组"示例(虽然我正在调用我的对象ItemSet)
该ItemSet部分编译得很好:
template<typename...Ts> class ItemSet { };
template<typename item_T, typename ...Ts>
class ItemSet<item_T, Ts...> : public ItemSet<Ts...>
{
public:
ItemSet(item_T t, Ts... item_types) : ItemSet<Ts...>(item_types...), tail(t) { }
protected:
item_T tail;
};
template <typename...M> struct type_holder;
template<typename T, typename ...M>
struct type_holder<0, ItemSet<T, M...>>
{ // ERROR: M parameter pack expects a type template argument.
typedef T type;
};
template <int k, typename T, typename ...M>
struct type_holder<k, ItemSet<T, M...>>
{
typedef typename type_holder<k - 1, ItemSet<M...>>::type type;
};
int main()
{
ItemSet<int, string, string, double> person(0, "Aaron", "Belenky", 29.492);
}
Run Code Online (Sandbox Code Playgroud)
但是,在注释掉的代码中,我在type_holder的声明中得到了编译器错误.我在相同的语法上尝试了很多变体,但始终存在相同的问题.
我正在使用Microsoft Visual Studio 2013,它应该完全支持模板编程和Variadic模板.
你明白编译器的错误是什么,你能解释一下吗?
当前的问题是,您正在定义type_holder没有通用模板的专业化.另外,还有一个简单的拼写错误(typeholder而不是type_holder).修复这两个问题使其与其他编译器一起编译:
template <int, typename T>
struct type_holder;
template <int k, typename T, typename ...M>
struct type_holder<k, ItemSet<T, M...>>
{
typedef typename type_holder<k - 1, ItemSet<M...>>::type type;
};
template<class T, class ...M>
struct type_holder<0, ItemSet<T, M...>>
{
typedef T type;
};
Run Code Online (Sandbox Code Playgroud)
您使用的编译器发出的错误并不是特别有用.我建议保留一些C++编译器只是周围用(我通常使用测试模板代码gcc,clang和英特尔的编译器).