我会使用Boost的MPL和Fusion库。有两种方法可以得到类型列表:生成它们或显式定义它们。前者更灵活,但由于我们不知道您如何获得所需值,很难说哪种方法适合您。
无论如何,如果要生成类型列表:
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/vector.hpp>
#include <array>
#include <iostream>
namespace bmpl = boost::mpl;
template <typename T>
struct make_array
{
static const std::size_t size = T::value * 2;
typedef std::array<int, size> type;
};
typedef bmpl::range_c<size_t, 1, 10> array_range;
typedef bmpl::transform<array_range, make_array<bmpl::_1>,
bmpl::back_inserter<bmpl::vector<>>
>::type array_collection;
或者明确地说明:
#include <boost/mpl/vector.hpp>
#include <array>
#include <iostream>
namespace bmpl = boost::mpl;
typedef bmpl::vector<
std::array<int, 2>,
std::array<int, 4>,
std::array<int, 6>,
std::array<int, 8>,
std::array<int, 10>,
std::array<int, 12>,
std::array<int, 14>,
std::array<int, 16>,
std::array<int, 18>
> array_collection;
无论哪种方式,您都可以像这样使用它:
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/mpl.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/mpl/for_each.hpp>
#include <typeinfo>
namespace bf = boost::fusion;
struct print_type
{
template <typename T>
void operator()(const T&) const
{
std::cout << typeid(T).name() << "\n";
}
};
struct print_values
{
template <typename T>
void operator()(const T& pArray) const
{
std::cout << "Printing array with size "
<< pArray.size() << ":\n";
std::for_each(pArray.begin(), pArray.end(),
[](int pX)
{
std::cout << pX << " ";
});
std::cout << std::endl;
}
};
int main(void)
{
bmpl::for_each<array_collection>(print_type());
std::cout.flush();
typedef bf::result_of::as_vector<array_collection>::type array_fusion;
array_fusion arrays;
bf::at_c<0>(arrays)[1] = 5;
bf::at_c<1>(arrays)[2] = 7;
bf::at_c<2>(arrays)[0] = 135;
bf::for_each(arrays, print_values());
}
std::vector
可能是最容易的选择。只要不改变大小就可以了。:) 诚然,它并不完全相同,但很干净。 - GManNickG