Можно ли вернуть элемент шаблона производного класса по базе?
Найдите следующие классы:
Data.h:
#include <string>
class IData{
public:
virtual ~IData(){};
virtual const std::string& getName() const = 0;
};
template <typename T>
class DataImpl: public IData
{
public:
DataImpl(const std::string& name, T* ptrToData)
:_name(name)
,_ptrToData(ptrToData)
{};
~DataImpl(){};
const std::string& getName() const
{
return _name;
}
const T* getDataPtr() const
{
return _ptrToData;
}
private:
std::string _name;
T* _ptrToData; // <-- how to return this pointer ?
};
Component.h:
#include <vector>
#include <string>
#include "Data.h"
class Component
{
public:
Component(const std::string& name)
:_name(name)
{};
~Component(){};
const std::string& getName() const
{
return _name;
};
std::vector<IData*>& getDataList()
{
return _dataList;
};
void addData(IData* ptr)
{
_dataList.push_back(ptr);
};
private:
std::string _name;
std::vector<IData*> _dataList;
};
main. cpp:
#include <iostream>
#include <vector>
#include <string>
#include "Component.h"
#include "Data.h"
int main()
{
// primitive types
int x = 5;
float y = 5.7;
bool b = false;
// complex structures
struct complex{
int a;
std::string c;
};
complex cx;
cx.a = 5;
cx.c = "anything";
DataImpl<int> d1("x", &x);
DataImpl<float> d2("y", &y);
DataImpl<bool> d3("b", &b);
DataImpl<complex> d4("complex", &cx);
Component cmp("cmpName");
cmp.addData(&d1);
cmp.addData(&d2);
cmp.addData(&d3);
cmp.addData(&d4);
std::vector<IData*>::iterator it = cmp.getDataList().begin();
for (;it != cmp.getDataList().end(); ++it)
{
IData* ptr = *it;
std::cout << ptr->getName() << std::endl;
}
return 0;
}
Внутри l oop в основном. cpp, я был доступ к каждому члену DataImpl. Но я хочу вернуть / получить переменную-член T * _ptrToData через базовый класс IData, но пока я не нашел никакого способа.
У меня есть ограничение компилятора для c ++ 98
Заранее спасибо.