I’m new to templates in C++, so here is my problem.
I’ve a generic class ProductItem that will do all the stuff I want, but I need to specialize a part in order to use pointers (for char*).
My code :
typedef unsigned char BYTE;
template<typename T>
class TProductTableItem
{
protected:
int Offset;
int DataLength;
T Value;
public:
virtual bool LoadFromBuffer(const BYTE* buffer, int count)
{
if(Offset + DataLength > count)
return false;
Value = buffer[Offset];
return true;
}
};
// Specialization (doesn't compile)
class TProductTableItemString : public TProductTableItem<char*>
{
bool LoadFromBuffer(const BYTE* buffer, int count)
{
if(Offset + DataLength > count)
return false;
memset(Value, 0, DataLength);
memcpy(Value, (void*)&buffer[Offset], DataLength);
return true;
}
};
When trying to compile this code, I’ve the following error message:
cannot convert from 'const BYTE' to 'char*'
What I’m doing wrong?
It look like that even for char* type, it tries to use the TProductTableItem::LoadFromBuffer function and not the TProductTableItemString::LoadFromBuffer one.
Thanks.
You are mixing two distinct concepts: inheritance and template specialization.
Your class is not a template specialization but it derives from a template instantiation. However that template cannot be instantiated because when
T = char *the statementValue = buffer[offset];has a type mismatch error.If you want to write a template specialization then the syntax is
Note that two templates instantiations are in general unrelated types from an inheritance point of view…
May be a solution for what you are trying to do is something like
I said may be because indeed it’s not clear to me what you are trying to accomplish.