我想知道如何使用可变参数模板来编写类似Boost MPL的vector_c。我已经写了下面的代码片段:MPL-like vector with variadic templates:Insertion
template <std::size_t element, std::size_t ... E>
struct vector
{
typedef vector<E ...> next;
static constexpr std::size_t size()
{
return sizeof... (E);
}
static constexpr std::size_t value()
{
return element;
}
};
template <std::size_t element>
struct vector<element>
{
// no need to define 'next' here
static constexpr std::size_t size()
{
return 1;
}
static constexpr std::size_t value()
{
return element;
}
};
您可能注意到,vector
必须在其中至少有一个元素,但是这是不是真的对我的限制。与上面的定义,它是很容易写“功能”,用于访问一个给定索引的元素:
template <std::size_t index, typename T>
struct get
{
typedef typename get<index - 1, typename T::next>::type type;
};
template <typename T>
struct get<0, T>
{
typedef T type;
};
例如,get<1, vector<1, 2, 3>>
返回正确的结果2
。现在我的问题:如何实现插入功能?我不使用MPL的原因是,当我尝试它的insert<>
时,它没有返回vector_c
。特别地,插入应适用这样的:
insert<vector<1, 3, 4>, 1, 2>::type
// ^ ^^
// type at element
其中必须收率vector<1, 2, 3, 4>
。那可能吗?
不错的解决方案 - 它有助于了解如何大量提升MPL可以重写或用可变参数模板取代。 – mark 2012-03-06 21:05:33
与此同时,我也得出结论,我必须写一个'push_front'函数 - 但是,我没有意识到它必须位于vector本身内部!我认为在矢量类之外编写push_front是不可能的,对吧? – cschwan 2012-03-07 09:47:35
@cschwan:当然你*可以*(例如:http://ideone.com/3F4UQ)。我只是不打算这么做。 – kennytm 2012-03-07 10:08:32