0

是否有任何类型的静态(编译器时)向量?例如,我可以通过给定的常量整数索引获取类型,如下所示

Vector<int, float>::Type<0> is int

Vector<int, float>::Type<1> is float
4

3 回答 3

4

如果要在编译时操作类型向量,可以使用boost::mpl::vectorBoost.MPL 库。但要小心,你的头可能会爆炸。

using namespace boost::mpl;

typedef at_c<vector<int, float>, 0>::type t1; // int
typedef at_c<vector<int, float>, 1>::type t2; // float

http://www.boost.org/doc/libs/1_54_0/libs/mpl/doc/refmanual/vector.html

于 2013-07-11T11:57:03.513 回答
3

Typelist in loki does exactly that. Loki is a library designed and developed by Andrei Alexandrescu. The whole library is template based. In particular, typelist (one of the basic components of the library) gives you plenty of compile-time algorithms which allow you to perform pretty much every operation you want to perform on a list (e.g. access by index, find, remove duplicates, ...). Typelist per se is extremely simple:

template <class T, class U> 
struct Typelist 
{ 
 typedef T Head; 
 typedef U Tail; 

}; 
namespace TL 
{ 
 ...typelist algorithms ... 
}

its power comes from the algorithms it provides. Such algorithms are all executed at compile-time.

The TypleList facilities are described in great detail in the book Modern C++ (Alexandrescu)

In particular, indexed access is implemented as:

template <class Head, class Tail> 
struct TypeAt<Typelist<Head, Tail>, 0> 
{ 
 typedef Head Result;
}; 
template <class Head, class Tail, unsigned int i> 
struct TypeAt<Typelist<Head, Tail>, i> 
{ 
 typedef typename TypeAt<Tail, i - 1>::Result Result; 
}; 

so that

TypeAt<MyList, 5>::Result a(...);

creates an object named "a" of the 6th type in MyList.

于 2013-07-11T06:23:55.847 回答
3

std::tuple已经提供了这个功能。

std::tuple_element<1, std::tuple<int, float>>::type // float
std::tuple_element<0, std::tuple<int, float>>::type // int
于 2013-07-11T12:26:56.740 回答