首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

模板的编译异常,错在哪里

2012-06-13 
模板的编译错误,错在哪里?从Modern C++ design里面摘出来的内容:C/C++ code#include stdafx.h// com

模板的编译错误,错在哪里?
从<<Modern C++ design>>里面摘出来的内容:

C/C++ code
#include "stdafx.h"// compile time programmingstruct nullType;struct emptyType{};template<class H, class T>struct typeList{    typedef H Head;    typedef T Tail;};template<class H>struct typeList<H, nullType>{    typedef H Head;};typedef typeList<char,         typeList<unsigned char,         typeList<wchar_t, nullType> > > charTypes;#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)>template<class H, class T>struct typeAt<typeList<H,T>,0>{ //这行编译错误    typedef H at;};template<class H,class T,size_t idx>struct typeAt<typeList<H,T>,idx>{    typedef    typename typeAt<T,idx-1>::at at;};int main(int argc,char**){    typeAt< TYPELIST_4<int,short,char,long>, 2> a=0;    return 0;}


VC编译错误提示:
1> my.cpp
1>my.cpp(24): error C2143: syntax error : missing ';' before '<'
1>my.cpp(24): error C2059: syntax error : '<'
1>my.cpp(24): error C2065: 'H' : undeclared identifier
1>my.cpp(24): error C2065: 'T' : undeclared identifier
1>my.cpp(24): error C2143: syntax error : missing ';' before '{'
1>my.cpp(24): error C2447: '{' : missing function header (old-style formal list?)
1>my.cpp(28): error C2923: 'typeAt' : 'idx' is not a valid template type argument for parameter 'T'
1> my.cpp(27) : see declaration of 'idx'
1>my.cpp(30): error C2977: 'typeAt' : too many template arguments
1> my.cpp(28) : see declaration of 'typeAt'
1>my.cpp(33): error C2079: 'a' uses undefined struct 'typeAt'
1>


[解决办法]
错误太多,不一一说了,下面的代码在 g++-4.7.0 上编译通过,你自己看我改了那里吧。
C/C++ code
#include <cstddef>struct nullType;struct emptyType{};template<class H, class T>struct typeList{ typedef H Head; typedef T Tail;};template<class H>struct typeList<H, nullType>{ typedef H Head;};typedef typeList<char,        typeList<unsigned char,        typeList<wchar_t, nullType> > > charTypes;#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)>template <typename,size_t> struct typeAt;template<class H, class T>struct typeAt<typeList<H,T>,0>{ typedef H at;};template<class H,class T,size_t idx>struct typeAt<typeList<H,T>,idx>{ typedef    typename typeAt<T,idx-1>::at at;};int main(int argc,char**){ typename typeAt< TYPELIST_4(int,short,char,long), 2>::at a=0; return 0;} 

热点排行