我會使用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