I'm trying to make a simple way to generate std::array
's at compile time. It's been a struggle so far to figure out a good way to pass a constexpr function in at compile time. The workaround I have found so far is like this.
#include <iostream>
#include <array>
namespace a {
constexpr int f(const int & i) { return i * i * i;}
#include "generate_with_function.hpp"
}
int main()
{
auto arr = a::generator<false,10,0>::array;
for (auto i : arr) {
std::cout << i << " ";
}
return 0;
}
this basically assumes you will define a function called f
and I wrapped it in a namespace incase I wanted to do a different one. I wanted to know if there is a more clever way to pass in the function and use it at compile time. Also here is the code that makes the list.
template <bool B, size_t Count,int ... Nums>
struct generator;
template <size_t Count>
struct generator<false,Count,0>
{
constexpr static std::array<int,Count> array
= generator<false,Count,1,f(0)>::array;
};
template <size_t Count, int Current, int ... Results>
struct generator<false,Count,Current, Results...>
{
constexpr static std::array<int,Count> array
= generator<Current+1==Count,Count,Current+1,f(Current), Results...>::array;
};
template <size_t Count, int Current, int ... Results>
struct generator<true,Count,Current,Results...>
{
constexpr static std::array<int,Count> array{{Results...}};
};
and before you ask no I don't actually have a real need for this.
As noted by @us2012 I should be specific about what I would rather have.
- nowrapping in namespace
- having to write the function but not actually passing it anywhere
- and not requiring the function to be named f