Also, as keskiverto suggests below, template specialization is how you would do this in the general case, but with functions you should just use overloading.
I know the function overloading technique. However in my case this is not quite feasible.
I am doing some matrix manipulations. So the number of types could be (theoretically) infinite. E.g., Matrix1d, Matrix2d, ... MatrixXd. In this case, I cannot overload a function potentially infinite times. If I know beforehand there's only a few types, then I could overload, but in this case how can I do that?
I don't understand, could you give an actual example of the function you're worried about?
@rafae11: typeid is for when you don't know the polymorphic runtime type of an object. In all other cases you should use std::is_same<typeA, typeB>::value
I am using Eigen library for matrix manipulations and I want to display the results. Let's say if the dimension of my vector is greater and equal than 2, then I can define the vector as Vector2d, Vector3d, Vector4d, ...
and call the member function .size() to determine the dimension.
If the problem is simple enough, say the vector dimension is only one, then I just want to simply define it as double. But in this case, there's no .size() function associated with that.
I want to write a generic display() function to show the results, both double and VectorXd type. But I just don't know how to achieve this.
Edit:
I can of course define a one dimensional variable using Eigen library as Matrix<double, 1, 1>, then I can call .size() member function. But my understanding is that using c++ built-in type like double would be more efficient.
Don't worry about efficiency - the only time you should change your code to improve performance is if something is obviously inefficient or if you have profiled your code and found the bottleneck.
In this case, the nice thing about templates is that they are inline by nature and so the compiler handles the optimization for you, and it decides how best to make it efficient.
Write generic code first, then optimize specific cases later.
IIRC, in Eigen a Vector is simply a Matrix where one of the dimensions has length 1.
So,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//The rows and columns may need to be switched around.
//I can never remember which is which.
template <typename ElementT, int Rows, int Columns>
struct MatrixPrinter{};
template <int Rows, int Columns>
struct MatrixPrinter<double, Rows, Columns>{
staticvoid print(const Matrix<double, Rows, Columns> &m){
//etc.
}
};
template <typename ElementT, int Rows, int Columns>
void print(const Matrix<ElementT, Rows, Columns> &m){
MatrixPrinter<ElementT, Rows, Columns>::print(m);
}