1

In this code create_matrix returns Matrix<int, 2, 3> type:

#include <array>
#include <iostream>

using namespace std;

template <class T, size_t ROW, size_t COL>
using Matrix = array<array<T, COL>, ROW>;

Matrix<int, 2, 3> create_matrix(int x, int y){
    Matrix<int, 2, 3> arr;
    arr[0][0] = 42;
    return arr;
}

int main(int argc, char *argv[])
{
    auto arr = create_matrix(2,3);
    cout << arr[0][0];
    return 0;
}

Is it possible to return Matrix<int, x, y> type?

dyp
  • 38,334
  • 13
  • 112
  • 177
zie1ony
  • 1,190
  • 2
  • 14
  • 33
  • possible duplicate of: http://stackoverflow.com/questions/2873802/specify-template-parameters-at-runtime – YoungJohn Feb 18 '14 at 20:08
  • ultimately template arguments must be deduced at compile time and so you cannot use runtime values to instantiate a template. – YoungJohn Feb 18 '14 at 20:09

2 Answers2

3

The template parameters for std::array must be known at compile time (either literal values, const values, or constexpr values, that are known at compile time)

So in this case it would not be possible to return a Matrix with x and y passed in at run time.

To get that type of functionality you might need to replace std::array with std::vector or some similar dynamic array type of object, and even then you would have to restructure the code not to take the values as template parameters.

YoungJohn
  • 946
  • 12
  • 18
1

It looks like the XY problem.

You could hack together a 2D "matrix" with vector<vector<int>> but that's sort of re-inveting the wheel in the shape of a hexagon (meaning: miserably poor performance).

I suggest you try a linear algebra library, for example Armadillo or Eigen.

Community
  • 1
  • 1
Ali
  • 56,466
  • 29
  • 168
  • 265