I wonder whether it is possible to implement multiple function of a template class without defining the template multiple times.
Declaration:
template <class T>
class Test{
private:
T field;
public:
Test(T value);
T& get();
void set(T value);
};
Implementation:
template <class T> Test<T>::Test(T value){ set(value); }
template <class T> T& Test<T>::get(){ return field; }
template <class T> void Test<T>::set(T value){ field = value; }
Copying template <class T> multiple times is somewhat error-prone. I wonder whether I can do something like this:
template <class T>{
Test<T>::Test(T value){ set(value); }
T& Test<T>::get(){ return field; }
void Test<T>::set(T value){ field = value; }
}
Any help would be appreciated.
You can directly implement those methods in the class definition.
Moreover, you don’t need to separate the declaration and implementation of the template class . It has no side effect to the compilation. Because the implementation is not the real implementation. A template class is not a class, it’s only a template that can be used to create a class. When you instantiate such a template class, e.g. YourTemplate, the compiler creates that new class. In order to create it, it has to see all the templated member functions (so that it can use the templates to create actual member functions such as YourTemplate::function1() ), and therefore these templated member functions must be in the header file, along with the template class body.