我会使用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;
// turns an index into an array
template <typename T>
struct make_array
{
// or whatever scheme you have
static const std::size_t size = T::value * 2;
// define generated type
typedef std::array<int, size> type;
};
// list of values to convert
typedef bmpl::range_c<size_t, 1, 10> array_range;
// transform that list into arrays, into a vector
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;
// list all array types
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>
// fusion "fuses" the bridge between MPL and runtime
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)
{
// print all the types you have
bmpl::for_each<array_collection>(print_type());
std::cout.flush();
// make a usable type out of the typelist
typedef bf::result_of::as_vector<array_collection>::type array_fusion;
array_fusion arrays; // now have an array of different arrays,
// compile-time generated but run-time usable
// access like this:
bf::at_c<0>(arrays)[1] = 5;
bf::at_c<1>(arrays)[2] = 7;
bf::at_c<2>(arrays)[0] = 135;
// for_each:
bf::for_each(arrays, print_values());
}
'的std ::矢量'可能会是最简单的。只是不要改变大小。诚然,它不完全相同,但它很干净。 – GManNickG 2010-07-28 00:17:56
是的,我已经有一个使用std :: vector而不是tr1 :: array的实现,但是使用动态大小是毫无意义的,因为它们可以在编译时计算,所以我一直在寻找一个静态解决方案。 – AkiRoss 2010-07-28 00:30:59
你可能会喜欢其中一个容器:http://www.boost.org/doc/libs/1_43_0/libs/fusion/doc/html/fusion/container.html。另外,如果您想回复某人,请使用@,就像@aaa – Anycorn 2010-07-28 00:42:38