我第一次尝试可变参数模板元编程,但一直遇到我无法追踪的编译器错误。
我正在关注 this page 上的“元组”示例(尽管我称我的对象为 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);
}
但是,在注释掉的代码中,我在 type_holder 的声明处遇到了编译器错误。 我尝试了相同语法的多种变体,但总是遇到相同的问题。
我正在使用 Microsoft Visual Studio 2013,它应该完全支持模板编程和可变参数模板。
你明白编译错误是什么吗,能给我解释一下吗?
最佳答案
直接的问题是您在没有通用模板的情况下定义 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;
};
您使用的编译器发出的错误不是特别有用。我建议保留一些 C++ 编译器来测试模板代码(我通常使用 gcc
、clang
和 Intel's compiler)。
关于c++ - 模板元编程,带有可变参数模板 : compiler error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27487470/