0

I have templated a variable.

This should be declared later in the code with the exact type. Can someone help me here for a solution/alternative for solve this problem?

(It must be declared beforehand, since it is addressed several times in the code)

int main(int argc, char* argv[]) { 
 
 template<typename MatType> 
 Matrix<MatType> A;
 
 ...

 while(program) {

   auto file = type_filename();

   intmatrix    = checkfile(file);
   doublematrix = checkfile(file);
 
   if (intmatrix)    { A = Matrix<int>(2,2);}
 
   if (doublematrix) { A = Matrix<double>(2,2);}
 
   program = waitforinput();

 }
andy
  • 41
  • 5

1 Answers1

0

In your pseudo-code, you have the type of A possibly changing in a loop depending on the return value of a call to a particular function, checkfile.

Understand that C++ is statically typed so this can't work. You need A to be a type that can hold different types of matrices; a variable of a matrix type cannot do that even if it is an instantiation of a template.

Your options are

  1. Make A be an std::variant<Matrix<int>,Matrix<double>>.
  2. Make A be an std::any.
  3. Possibly redesign your code such that all of this logic occurs in a function template that is either parametrized on an int or a float.
jwezorek
  • 8,592
  • 1
  • 29
  • 46