이 문제를 어떻게 해결해야 하나요 c++템플목록은 컴파일한 오류?

StackOverflow https://stackoverflow.com/questions/2150618

  •  23-09-2019
  •  | 
  •  

문제

(에서 독서 3 장의 현대적인 c++디자인)

목록.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

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’

표시되는 이유는 무엇입니까이 오류가?이 문제를 어떻게 해결해야 하나요?

도움이 되었습니까?

해결책

Looks like you're missing a forward declaration.

This is a partial specialization:

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;

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.


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.

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

다른 팁

목록을 재귀적으로 사용:그것이 기대하는 두 번째 templater 매개 변수 중 하나가 될 또 다른목록,또는 NullType(신호의 끝을 재귀).

을 정의하 foo 이메일로 문의하시기 바랍니다:

TYPELIST_2(int, double) foo;

또는,당신이 원하는 경우를 방지하는 매크로:

Typelist<int, Typelist<double, NullType> > foo;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top