如何解决这个c ++ typelist模板编译错误? [英] how do I fix this c++ typelist template compile error?

查看:178
本文介绍了如何解决这个c ++ typelist模板编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(从阅读现代c ++设计的第3章)

(from reading chapter 3 of modern c++ design)

typelist.hpp:

typelist.hpp:

class NullType {};

struct EmptyType {};


template <class T, class U>
struct Typelist
{
  typedef T Head;
  typedef U Tail;
};

#define TYPELIST_1(T1) Typelist<T1, NullType>
#define TYPELIST_2(T1, T2) Typelist<T1, TYPELIST_1(T2) >
#define TYPELIST_3(T1, T2, T3) Typelist<T1, TYPELIST_2(T2, T3) >
#define TYPELIST_4(T1, T2, T3, T4) Typelist<T1, TYPELIST_3(T2, T3, T4) >
#define TYPELIST_5(T1, T2, T3, T4, T5) Typelist<T1, TYPELIST_4(T2, T3, T4, T5) >
#define TYPELIST_6(T1, T2, T3, T4, T5, T6) Typelist<T1, TYPELIST_5(T2, T3, T4, T5, T6) >


namespace TL
{
  template <class TList> struct Length;
  template <> struct Length<NullType>
  {
    enum { value = 0 };
  };

  template <class T, class U>
    struct Length< Typelist<T, U> >
    {
      enum { value = 1 + Length<U>::value };
    };


  template <class Head, class Tail>
    struct TypeAt<Typelist<Head, Tail>, 0>
    {
      typedef Head Result;
    };

  template <class Head, class Tail, unsigned int i>
    struct TypeAt<Typelist<Head, Tail>, i>
    {
      typedef typename TypeAt<Tail, i-1>::Result Result;
    };

}

main.cpp

#include "typelist.hpp"

Typelist<int, double> foo;

int main() {
}

g ++ main。 cpp

g++ main.cpp

typelist.hpp:37: error: ‘TypeAt’ is not a template
typelist.hpp:43: error: type/value mismatch at argument 2 in template parameter list for ‘template<class Head, class Tail> struct TL::TypeAt’
typelist.hpp:43: error:   expected a type, got ‘i’

为什么会收到此错误?如何解决此问题?

Why do I get this error? How do I fix this?

推荐答案

看起来您缺少转发声明。

Looks like you're missing a forward declaration.

这是一个部分特化:

template <class Head, class Tail>
struct TypeAt<Typelist<Head, Tail>, 0>

但是编译器不知道它是什么特殊化。添加它之前:

But the compiler has no idea what it's a specialization of. Add this before it:

template <class List, unsigned Index>
struct TypeAt;

这让编译器知道:有一个类 TypeAt 其中有两个模板参数。所以现在当你专门化它,编译器知道你正在谈论什么类。

This let's the compiler know: "There is a class TypeAt which has two template parameters." So now when you specialize it, the compiler knows what class you're talking about.

注意, code> Typelist 不正确。这些算法是标记终止。这意味着,像C字符串,他们期望数据以特殊值结束。在我们的例子中,这是 NullType

Note, your usage of Typelist is incorrect. These algorithm's are sentinel-terminated. This means, like C-strings, they expect the data to be concluded with a special value. In our case, this is NullType.

因此,采取Éric的建议。 (即提示:如果你发现他的答案有帮助,向上投票。)

So, take Éric's advice. (i.e. hint: if you found his answer helpful, up-vote it.)

这篇关于如何解决这个c ++ typelist模板编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆