I have a struct with a class member I'd like to make const because it should never be changed after the constructor:
struct S
{
S(const double pp) : p(pp){}
const double p;
};
However, I would like to create an std::array
of S
, of size 1000 (a size too large to explicitly construct each element).
I am aware STL array elements need a default constructor.
Is it possible to define a function called create_array()
which can be used like this:
const double p = from_config("p");
std::array<S, 1000> = create_array(p);
and allow me to keep the class member as const?
Is it possible to define a function called
create_array()
which can be used like this:std::array<S, 1000> = create_array(p);
Yes, it is possible to do exactly this as shown below:
#include <array>
#include <iostream>
struct S
{
S(const double pp) : p(pp){}
const double p;
};
template <typename T, std::size_t ...I>
constexpr auto make_array(std::index_sequence<I...>, double p) {
return std::array<T, sizeof...(I)>{((I-I), p)...};
}
//version that forwards/passes the args
template<typename T, std::size_t N>
constexpr auto create_array(double p) {
return make_array<T>(std::make_index_sequence<N>(), p);
}
int main(void)
{
const double p = 5.5;
auto a = create_array<S, 5>(p);
for(const auto &elem: a)
{
std::cout << elem.p << "\n";
}
return 0;
}
The output of the program is:
5.5
5.5
5.5
5.5
5.5