#Template Class
10 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
u can
l.h
template<typename T>
class Solution{
int a ();
};
l.cpp
#include "l.h"
template<typename T>
int Solution<T>::a(){
return 2;
}
U can define them like this
Hi Muz. You can define the member functions (if you're talking about their implementations) in a cpp file.
Note that template classes are generally meant to be used with any type. If you put the implementation in a cpp file, you have to specify (as to my knowldge) for which type you want to implement it - this would limit the number of types you can use it with.
I did something similar in my project: I defined my template class structure in Vector.hpp and put the implementations into Vector.cpp - limiting to int and float only as for the data types.
Example:
// Vector.hpp
template <typename T> class Vector2 {
public:
Vector(T x, T y);
// ...
};
// aliases just for convenience; you don't need them
using Vector2i = Vector2<int>;
using Vector2f = Vector2<float>;
// Vector.cpp
template <typename T> Vector2<T>::Vector2(T x, T y) {
this->x = x;
this->y = y;
}
// ...
// this is the important part, to tell the compiler which types to compile your template for:
template class Vector2<int>;
template class Vector2<float>;
You can see the full implementation of my use case here:
Awesome thanks. Idk what i did wrong. I'll follow up tomorrow and say if it works.
With what tenry mentioned above. Is it required that I mention all types? I cant really do that since that is the point of me templating
I believe you have. Usually templates are implemented in headers, so users can choose any type and the implementations happen in-place/inline using the given types.
But if you "hide" the implementation behind cpp files, users can not inject any types and depend on the implementation (using given type) to exist. But if you don't define the desired types in your cpp file, your compiler would maybe assume it does not need to compile for any type the the related .o/.obj file would just be empty 😄
Alr thanks alot. I figured that was the case. I'll just define in the header
@random remnant Has your question been resolved? If so, type !solved :)
!solved