Inspired by this question : c++ generate (xyz) points in range
I began to wonder whether there is a form of template code that can, from this statement:
using X = axis_limits<-10, +10>;
using Y = axis_limits<-10, +10>;
using Z = axis_limits<-10, +10>;
auto space = std::vector<point>{ generate_point_space<X, Y, Z> };
construct at compile time a vector called space that contains one point for each x, y , z where begin(X) <= x < end(X)... etc for y and z.
Order is not important.
The return type of generate_point_space<>
should be std::initializer_list<int>
or similarly compile-time-constructed sequence. I'm not looking to generate a sequence of calls to push_back()
. That would be too easy :)
struct point
would have a constructor of the form:
point::point(int x, int y, int z)
a single dimension of ints is straightforward (code below). The multi-dimensional aspect of the problem is beyond me today
#include <utility>
#include <iostream>
#include <vector>
template<int Begin, int End>
struct axis_limits
{
static constexpr int first = Begin;
static constexpr int last = End;
};
namespace details
{
template<typename Int, typename, Int Begin, bool Increasing>
struct integer_range_impl;
template<typename Int, Int... N, Int Begin>
struct integer_range_impl<Int, std::integer_sequence<Int, N...>, Begin, true> {
using type = std::integer_sequence<Int, N+Begin...>;
};
template<typename Int, Int... N, Int Begin>
struct integer_range_impl<Int, std::integer_sequence<Int, N...>, Begin, false> {
using type = std::integer_sequence<Int, Begin-N...>;
};
}
template<typename Int, Int Begin, Int End>
using integer_range = typename details::integer_range_impl<
Int,
std::make_integer_sequence<Int, (Begin<End) ? End-Begin : Begin-End>,
Begin,
(Begin<End) >::type;
template<int...Is>
std::vector<int> make_vector(std::integer_sequence<int, Is...>)
{
return std::vector<int> { Is... };
}
template<int Begin, int End>
struct axis_range
{
using sequence_type = integer_range<int, Begin, End>;
static constexpr int size = sequence_type::size();
static std::vector<int> as_vector()
{
return make_vector(sequence_type {});
}
};
template< int Begin, int End >
std::vector<int> make_axis(const axis_limits<Begin, End> &)
{
return axis_range<Begin, End>::as_vector();
}
template<class T>
void dump_vector(std::ostream& os, const std::vector<T>& v) {
const char* sep = "{ ";
for(const auto& i : v) {
os << sep << i;
sep = ", ";
}
os << " }";
}
template<class T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec)
{
dump_vector(os, vec);
return os;
}
using namespace std;
int main()
{
using X = axis_limits<-5, +5>;
auto space = std::vector<int>(make_axis(X{}));
cout << space << endl;
return 0;
}
current output:
{ -5, -4, -3, -2, -1, 0, 1, 2, 3, 4 }
what I am looking for:
{ { -10, -10, -10 }, { -10, -10, -9 } .... { 9, 9, 8 }, { 9, 9, 9 } }