I want to be able to create an array of calculated values (let\'s say for simplicity\'s sake that I want each value to be the square of it\'s index) at compile time using t
I really like j_random_hackers answer - its beautiful and short. With C++11, one can extend this to
template <int I>
struct squared {
squared<I - 1> rest;
static const int x = I * I ;
constexpr int operator[](int const &i) const { return (i == I ? x : rest[i]); }
constexpr int size() const { return I; }
};
template <>
struct squared<0> {
static const int x = 0;
constexpr int operator[](int const &i) const { return x; }
constexpr int size() const { return 1; }
};
This code is usable both at run time
squared<10> s;
for(int i =0; i < s.size() ; ++i) {
std::cout << "s[" << i << "]" << " = " << s[i] << std::endl;
}
as well as compile time
struct Foo {
static const squared<10> SquareIt;
enum {
X = 3,
Y = SquareIt[ X ]
};
};
int main() {
std::cout << "Foo::Y = " << Foo::Y << std::endl;
}
and provides a nice and readable syntax.