Reputation: 227
I have a template class like this
//Matrix.h
template <class T = double>
class Matrix
{
//some constructors variables and ...
};
defined in a file called Matrix.h now how can I return an object from this class in other file say assemble.h something like:
//assemble.h
#include "Matrix.h"
Matrix<T> assemble(Matrix<T> KG,int node)
{
//some other codes
}
Upvotes: 0
Views: 4433
Reputation: 27528
[Matrix template] defined in a file called Matrix.h now how can I return an object from this class in other file say assemble.h
Matrix
is not a class in itself. It's a template; view it as a means to create classes, e.g. Matrix<int>
, Matrix<std::string>
, Matrix<double>
or Matrix<MyClass>
.
Therefore, the question is: Do you want your assemble
function to work with any matrix class or do you want it to work one particular matrix class?
In the former case, you must templatise the function as well (which means that, similar to what happened above, you no longer have a function but a function-creation mechanism):
template <class ContentType>
Matrix<ContentType> assemble(Matrix<ContentType> KG, int node)
{
// ...
}
(I've named the template parameter ContentType
in this example, just so that you can see it does not have to be the same name as the template parameter in Matrix
.)
In the latter case, you must specify the concrete class:
Matrix<int> assemble(Matrix<int> KG, int node)
{
// ...
}
By the way, you may want to pass your matrix objects by const reference, especially in the absence of C++11 move features.
Upvotes: 2
Reputation: 23793
assemble
needs to be a template function as well :
template<typename T>
Matrix<T> assemble(Matrix<T> KG,int node)
{
Matrix<T> m;
//some other codes
return m;
}
Note:
KG
as a reference-to-const, instead than by valueUpvotes: 1