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》上有詳細說明。ios
這本書在豆瓣上的評分高達9.0,雖然比不上《The C Programming Language》的9.5,但卻比Herb Sutter的《Exceptional C++》的8.5分要高上很多。
code