您的位置:首页 > 编程语言 > C语言/C++

VC6不支持typedef中递归。终于找到了Tuple的实现方案。

2008-09-18 22:21 399 查看
众所周知,VC6对Templates的支持非常差,但是由于工作需要,我还是希望能够在VC6上实现一个Tuple,这个好像比实现remove_reference还难了(boost好像也没有实现一个VC6下可运行的Tuple),因为Tuple的实现中用到typedef的递归,这种方式VC6会出现死循环。我做了一个简化的测试工程,请高手帮忙看看有没有好的办法绕过这个问题?多谢!
代码如下:(如果用enum部分进行递归,VC6下能正确运行)


#include <iostream.h>




template <typename T, int n>


struct Get


{


template <int unused>


struct GetInner


{


//enum { Value = Get<T, n+1>::Value};


typedef Get<T, n+1>::Type Type;


};




template <>


struct GetInner<2>


{


//enum { Value = 100};


typedef int Type;


};




//enum { Value = GetInner<n>::Value};


typedef GetInner<n>::Type Type;


};




int main()


{


//cout << Get<int, 0>::Value <<endl;


typedef Get<int, 0>::Type TmpType;


cout << typeid(TmpType).name() <<endl;


return 0;


}

借鉴了boost的一段代码,解决了VC6下实现Tuple的问题:
注释掉的部分是原来有问题的实现,为何boost的解决方案可行,还没来得及仔细研究,如果您知道,请告诉我:)


/*


template<


typename Typelist,


int Index, //requested element index


int Step = 0, //current recusion step


bool Stop=(Index==Step), //stop recusion flag


bool OutOfRange = Length<Typelist>::Value==0 //out of range flag


>


struct Get


{


template<bool unused1, bool unused2>


struct GetInner


{


typedef typename Get<typename Typelist::tail, Index, Step+1>::Type Type;


};




// found


template<>


struct GetInner<true, false>


{


typedef typename Typelist::head Type;


};


// found


template<>


struct GetInner<true, true>


{


typedef typename Typelist::head Type;


};


template<>


struct GetInner<false, true>


{


//if OutOfRange is 'true' the 'type' is undefined


//so we'll get a compile-time error


};




typedef GetInner<Stop, OutOfRange>::Type Type;




};


*/




// Workaround the lack of partial specialization in some compilers


template<int N>


struct _element_type


{


template<typename Tuplelist>


struct inner


{


private:


typedef typename Tuplelist::tail tail;


typedef _element_type<N-1> next_elt_type;




public:


typedef typename _element_type<N-1>::template inner<tail>::RET RET;


};


};




template<>


struct _element_type<0>


{


template<typename Tuplelist>


struct inner


{


typedef typename Tuplelist::head RET;


};


};




// Return the Nth type of the given Tuple


template<typename Tuplelist, int N>


struct Get


{


private:


typedef _element_type<N> nth_type;




public:


typedef typename nth_type::template inner<Tuplelist>::RET RET;


typedef RET Type;


};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 递归 VC6 Template Tuple
相关文章推荐