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

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

2014-01-12 00:00 671 查看
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;
}


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

这本书在豆瓣上的评分高达9.0,虽然比不上《The C Programming Language》的9.5,但却比Herb Sutter的《Exceptional C++》的8.5分要高上不少。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息