I would like to now if the following is possible.
I have a templated class called A
which inherits from a class called Base
. In Base
I set a write()
function to be rewritten for every derived class.
I am creating a vector to store the references of the Base
objects to be printer latter (dataBase
).
I would like to know if it is possible to retrieve the reference of the A
object whose reference I passed to dataBase
.
I have the following code:
#include <iostream>
#include <string>
#include <array>
#include <vector>
class Base
{
public:
Base(std::string name):name_(name){}
virtual ~Base(){}
virtual void write()=0;
const std::string& name() const
{
return name_;
}
private:
std::string name_;
};
template< typename T>
class A : public Base
{
public:
A(std::string name):Base(name),name2_(name + "test"){}
~A(){}
void write();
std::string name2_;
};
template< typename T>
void A<T>::write()
{
std::cout << name2_ << std::endl;
}
int main()
{
A<int> one("one");
A<double> two("two");
A<std::array<double,4>> three("three");
std::vector<Base*> dataBase;
dataBase.push_back(&one);
dataBase.push_back(&two);
dataBase.push_back(&three);
for(auto i : dataBase)
{
i->write();
}
A<int>& getOne = lookup("one"); // this is what I want to create
getOne.name2_ = "worked";
for(auto i : dataBase)
{
i->write();
}
return 0;
}
Best Regards
Aucun commentaire:
Enregistrer un commentaire