假设我有以下类定义:
template <unsigned int N>
class foo
{
boost::tuples::tuple<...> bar;
};
给定编译时常量 N
, 我想扩展 bar
的类型成为一个包含 N
的元组指定类型的元素。即foo<2>::bar
的类型将是 boost::tuples::tuple<T, T>
.我猜我可以使用 Boost.MPL为此,但我还没有弄清楚确切的顺序。我想我可以这样做:
template <typename T, int N>
struct type_repeater
{
typedef typename boost::mpl::fold<
boost::mpl::range_c<T, 0, N>,
boost::mpl::vector<>,
boost::mpl::push_back<_1, T>
>::type type;
};
那么例如type_repeater<T, 2>::type
相当于 boost::mpl::vector<T, T>
.我只是不确定如何/是否可以获取该类型列表并将其注入(inject)到元组的参数列表中,就像我想要的那样。这可能吗?
最佳答案
这似乎是一个很好的使用 C++11 的最小示例
#include <tuple>
template <unsigned int N, typename T>
struct type_repeater {
typedef decltype(std::tuple_cat(std::tuple<T>(), typename type_repeater<N-1, T>::type())) type;
};
template <typename T>
struct type_repeater<0, T> {
typedef decltype(std::tuple<>()) type;
};
int main() {
type_repeater<3, float>::type asdf;
std::get<0>(asdf);
std::get<1>(asdf);
std::get<2>(asdf);
}
关于c++ - 如何创建具有指定数量的元素(相同类型)的 boost::tuple?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20711721/