I’m working with the templated Matrix class in the Eigen linear algebra library (link). The Matrix class takes three nominal template parameters:
Matrix<type, rows, cols>
In the above, an example of type is double, or std::complex<double>. In addition, rows is the number of rows, and cols is the number of columns in the Matrix.
As shown by the code below, what I would like to do is use a different templated Matrix class at run-time using a conditional statement.
The first solution that comes to mind might be to use void pointers.
#include <iostream>
#include <Eigen/Dense>
#include <complex>
using namespace Eigen;
int main()
{
// this flag is set at run-time, but it is only set here
// in the code as an example
int create_complex = 1;
void *M;
if(create_complex)
{
Matrix<std::complex<double>,3,3> m0;
M = &m0;
}
else
{
Matrix<double,3,3> m0;
M = &m0;
}
// de-reference pointer here and use it
return 0;
}
Although this code compiles, the void *M pointer needs to be explicitly de-referenced before use. This is inconvenient, since I then have to write different code blocks for the same program logic.
I am wondering if there is something similar to polymorphism that might be applied here, where I don’t have to use void pointers.
You should templatize your method too:
UPDATE
Or you can define your class
you can switch these definitions with preprocessor definition.