首页 > 编程语言 > 详细

将任意类型映射到一个唯一整数(C++模板实现TypeList)

时间:2014-01-16 00:08:40      阅读:440      评论:0      收藏:0      [点我收藏+]

From: http://stackoverflow.com/questions/1708458/template-metaprogram-converting-type-to-unique-number

bubuko.com,布布扣
template <class Prev, class This>
class TypeList
{
public:
   enum
   {
      position = (Prev::position) + 1,
   };
};

template <>
class TypeList<void, void>
{
public:
  enum
  {
     position = 0,
  };
};


#include <iostream>

int main()
{
        typedef TypeList< void, void> base;  // base
        typedef TypeList< base, double> t2;  // position is unique id for double
        typedef TypeList< t2, char > t3; // position is unique id for char

        std::cout << "T1 Posn: " << base::position << std::endl;
        std::cout << "T2 Posn: " << t2::position << std::endl;
        std::cout << "T3 Posn: " << t3::position << std::endl;
}
bubuko.com,布布扣

确实是非常巧妙的方法。这个方法在Andrei Alexandrescu的《Modern C++ Design》上有详细说明。

这本书在豆瓣上的评分高达9.0,虽然比不上《The C Programming Language》的9.5,但却比Herb Sutter的《Exceptional C++》的8.5分要高上不少。

将任意类型映射到一个唯一整数(C++模板实现TypeList)

原文:http://www.cnblogs.com/wxwidgets/p/3516664.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!