Making a template meta function to create a unit matrix at compile time

Viewed 543

I was asking myself if it is possible to create a unit matrix at compile time if size is known. So far I just wrote an example creating a std::vector based matrix with a fixed size, e.g. 4x4. However, I am not sure how to set the values. I guess, I need recursion :/

// Example program
#include <iostream>
#include <string>
#include <vector>

template <class T>
using vec1D = std::vector<T>;

template <class T>
using vec2D = std::vector<std::vector<T>>;

template <class T, int size>
vec2D<T> make_mat() {
  vec2D<T> mat(size, vec1D<T>(size));
  return mat;
}

int main()
{
  vec2D<float> unit = make_mat<float, 4>();
  std::cout 
  << unit[0][0] << unit[0][1] << unit[0][2] << unit[0][3] << std::endl
  << unit[1][0] << unit[1][1] << unit[1][2] << unit[1][3] << std::endl
  << unit[2][0] << unit[2][1] << unit[2][2] << unit[2][3] << std::endl
  << unit[3][0] << unit[3][1] << unit[3][2] << unit[3][3] << std::endl;
}
2 Answers
Related