我将首先转储代码,稍后在必要/适当的地方添加引用和注释。如果结果与您正在寻找的结果有点接近,请发表评论。
包扩展的索引技巧(此处需要应用生成器),由Xeo从这个答案修改为使用std::size_t
而不是unsigned
.
#include <cstddef>
// by Xeo, from https://stackoverflow.com/a/13294458/420683
template<std::size_t... Is> struct seq{};
template<std::size_t N, std::size_t... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...>{};
template<std::size_t... Is>
struct gen_seq<0, Is...> : seq<Is...>{};
生成器功能:
#include <array>
template<class Generator, std::size_t... Is>
constexpr auto generate_array_helper(Generator g, seq<Is...>)
-> std::array<decltype(g(std::size_t{}, sizeof...(Is))), sizeof...(Is)>
{
return {{g(Is, sizeof...(Is))...}};
}
template<std::size_t tcount, class Generator>
constexpr auto generate_array(Generator g)
-> decltype( generate_array_helper(g, gen_seq<tcount>{}) )
{
return generate_array_helper(g, gen_seq<tcount>{});
}
使用示例:
// some literal type
struct point
{
float x;
float y;
};
// output support for `std::ostream`
#include <iostream>
std::ostream& operator<<(std::ostream& o, point const& p)
{ return o << p.x << ", " << p.y; }
// a user-defined generator
constexpr point my_generator(std::size_t curr, std::size_t total)
{
return {curr*40.0f/(total-1), curr*20.0f/(total-1)};
}
int main()
{
constexpr auto first_array = generate_array<5>(my_generator);
constexpr auto second_array = generate_array<10>(my_generator);
std::cout << "first array: \n";
for(auto p : first_array)
{
std::cout << p << '\n';
}
std::cout << "========================\n";
std::cout << "second array: \n";
for(auto p : second_array)
{
std::cout << p << '\n';
}
}