0

I have the following template class:

#ifndef T_SIMPLE_MATRIX_H
#define T_SIMPLE_MATRIX_H


template<class T, int N>
class SMatrix {
  private:

    T v[N*N];

  public:

    SMatrix<T, N>(){}

    T& operator() (int r, int c){
        return  v[N*r+c];
    }
    const T& operator()(int r, int c) const{
        return  v[N*r+c];
    }



};

#endif // 

And the following main code:

    ifstream fi(argv[1]);

    int N;
    fi >> N;

    for (int i = 0; i < N; i++) {
        int M;
        fi>>M;
        cout << "Matrix size " << M << endl;
        SMatrix<double, M> A;
    }

This code fails at main.cpp and gives the error: "non-type template argument of type 'int' is not an integral constant expression". It works when I change M to 2, what can I do to pass ifstream value to the template?

cppisnice
  • 13
  • 2
  • 5
    Templates need to be instantiated at compile time. How is the compiler supposed to do that if which template it instantiates depends on a run time value? You might want to read a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Rakete1111 Jan 29 '18 at 14:54
  • You can't instantiate template with runtime value – user2807083 Jan 29 '18 at 14:54
  • You can't - `M` is a not a constant compile-time expression, you cannot use it as a template parameter. Do you really need to have `N` as a template parameter in your class? Couldn't you just use a `std::vector` here instead of `T[N*N]`? – Holt Jan 29 '18 at 14:55

1 Answers1

-1

Template parameters must be known at compile time, eg.

SMatrix<int, 10> A;

Value of M is known at runtime, so it can't be used as a template parameter.

You should make N a constructor's argument and use dynamic allocation:

std::unique_ptr<T[]> v;
v.reset(new T[N * N]);
  • 4
    Please do not encourage such usage of dynamic allocation, a `std::vector` would be much better suited here. – Holt Jan 29 '18 at 15:00