I'm writing a small tensor library (inspired from here: http://www.wlandry.net/Projects/FTensor), relying on C++11 or 14.
For the sake of clarity, I would like to access the indices starting from 1 ,and not 0. For instance, for a vector v, use v(1), v(2) and v(3) to access its components, stored in a regular 1D array. (edit: This is for a continuum mechanics application. People are used to start at 1. Yes, it is un-natural for programmers.)
Now, I already now how to do it at run time. I would like to know if we can avoid this computation at runtime, as it get more complex for higher order tensors in case of symmetries.
I found this way of writing a compile time map where i manually put the shift: https://stackoverflow.com/a/16491172/1771099
However, using the code in the SO answer above, I cannot do something like this:
for i=1; i<4;i++){
std::cout << mymap::get<i>::val << std::endl;
}
since i is not known a compile time. Is there a smart way to do it ? Build a kind of static map, for each tensor order and symmetry, than we can lookup at runtime ?
Thanks
Edit: Here is what I consider "bad". The constexpr are actually useless
// subtract 1 to an index
inline constexpr size_t
sub_1_to_idx(size_t const &i) {
return i - 1;
}
// build a parameter pack from (a,b,c,...) to (a-1,b-1,c-1,...)
template<typename... idx>
constexpr std::array<size_t, sizeof...(idx)>
shift_idx(const idx &... indices) {
return std::array<size_t, sizeof...(idx)>
{{sub_1_to_idx(indices)...}};
};
//use this to return an index of a 1D array where the values of a possibly multidimentional, possibly symmetric Tensor are stored.
template<>
template<typename... idx>
size_t
TA_Index<2, Tsym::IJ>::of(const idx&... indices) {
static_assert(sizeof...(indices) == 2, "*** ERROR *** Please access second order tensor with 2 indices");
const std::array<size_t, sizeof...(idx)> id = shift_idx(indices...);
return id[0] > id[1] ? (id[0] + (id[1] * (2 * 3 - id[1] - 1)) / 2)
: (id[1] + (id[0] * (2 * 3 - id[0] - 1)) / 2);