Reputation: 3
I have a template class like this
template <class DatasetType>
class DataHandler
{
void Action(DatasetType* Test)
{
//
}
}
and then I need to store in an array this template class
class Factory{
vector<DataHandler<BaseData>*> availableData;
void SetAvailableData(vector<DataHandler<BaseData>*> i_availableData)
{
this->availableData= i_availableData;
}
}
BaseData is a base class
class BaseData
{
virtual void HandleData() = 0;
}
My problem is that when I try to put something in the array that is inherit of BaseData
class DataType1: public BaseData
{
void HandleData() override;
}
...
vector<DataHandler<DataType1>*> arrayWithData = vector<DataHandler<DataType1>*>();
factory->SetAvailableData(arrayWithData );
...
Error E0312 "no suitable user-defined conversion from std::vector < DataHandler < DataType1 > * > to std::vector < DataHandler < BaseData > * >
I thought that the very reason to use inherit was that no conversion would be needed. In an array of BaseData[] I could store DataType1? DataHandler needs to be able to 'handle' any data type, but in this specific situation Factory needs to be able to store everything that inherits from only BaseData. What am I doing wrong? How do I fix this?
-edit-
ok basically what I want is that DataHandler is only a base class, and I need to create different DataHandlers that inherits from this base class.
BaseData contains basic operations with generic data, and I need to create other data types that inherits from BaseData
My original problem was that when I want to use DataHandler I used it as such
DataType1* dataType = new DataType1();
handler->Start(dataType);
void DataHandler2::Start(DataBase* data)
{
DataType1* newData= dynamic_cast<DataType1*>(data);
}
in my handler I always had to do dynamic casts, and it looked really bad that I had to do dynamic casts in every function of DataHandlers I tried to solve this with the use of class template
Upvotes: 0
Views: 110
Reputation: 40080
Even though DataType1
inherits from BaseData
(and pointers and references from the former can implicitly be converted to pointers and references to the latter), DataHandler<DataType1>
and DataHandler<BaseData>
are unrelated types.
You cannot convert a DataHandler<BaseData>
to/from a DataHandler<DataType1>
without providing a user-defined conversion. Once this is done, since you cannot define a conversion from/to std::vector<DataHandler<BaseData>>
to/from std::vector<DataHandler<DataType1>>
, you need to write a conversion function for this last step.
Upvotes: 2