Is it posible to write implementation of non template method in template class(struct) at .cpp file? I have read that template method should be written on .h, but my method is not template method although it belongs to template class. Here is the code in my .h:
#include <iostream>
#ifndef KEY_VALUE_H
#define KEY_VALUE_H
using namespace std;
namespace types
{
template <class T, class U>
struct key_value
{
T key;
U value;
static key_value<T, U> make(T key, U value)
{
key_value<T, U> kv;
kv.key = key;
kv.value = value;
return kv;
};
string serialize()
{
// Code to serialize here I want to write in .cpp but fails.
}
};
}
#endif /* KEY_VALUE_H */
I tried to write the implementation of method serialize()
in .cpp file like this:
#include "key_value.h"
using namespace types;
template <class T, class U>
string key_value<T, U>::serialize()
{
// Code here returning string
}
Ended up with error: Redefinition of 'serialize'
How is the proper way to doing this?
A non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.
Deriving from a non-template base class There is no requirement that your base class be a template. It is quite possible to have a template class inherit from a 'normal' class. This mechanism is recommended if your template class has a lot of non-template attributes and operations.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
There is no difference. typename and class are interchangeable in the declaration of a type template parameter.
It's not possible*. Think about why templates need to be in header files in the first place: so that every .cpp file which uses code instantiated from a template can access it (templates are instantiated on demand only).
So in a way, you can think of a class template as a template for data layout (data members) plus a set of templates, one for each member function. Therefore, all members of a template class are treated as templates. You can even explicitly specialise a member function of a class template.
* As always, if explicit instantiation is an option, you can define the member function in a .cpp file and provide all required expicit instantiations in that .cpp file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With