Cast a polymorphic smart pointer object - c++

I implemented the following smart pointer template class:
#ifndef __ProjectManager__mSharedPtr__
#define __ProjectManager__mSharedPtr__
#include <stdio.h>
#include "RefCount.h"
template <class T>
class mSmartPtr {
T *data;
RefCount *rc;
public:
mSmartPtr(T* srcPtr);
mSmartPtr(const mSmartPtr&);
~mSmartPtr();
T* operator->() const;
T& operator*() const;
mSmartPtr<T>& operator=( mSmartPtr&);
mSmartPtr<T> operator()(mSmartPtr&);
};
template<class T>
mSmartPtr<T> mSmartPtr<T>::operator()(mSmartPtr<T>& src) {
return dynamic_cast<??>(src);
}
template <class T>
mSmartPtr<T>::mSmartPtr(T *srcPtr):
data(srcPtr) {
rc = new RefCount();
rc->add();
}
template<class T>
mSmartPtr<T>::~mSmartPtr() {
if (rc->remove() == 0) {
delete data;
delete rc;
}
}
template<class T>
mSmartPtr<T>::mSmartPtr(const mSmartPtr<T> &src):
data(src.data), rc(src.rc) {
rc->add();
}
template <class T>
T* mSmartPtr<T>::operator->() const {
return data;
}
template<class T>
T& mSmartPtr<T>::operator*() const {
return &data;
}
template <class T>
mSmartPtr<T>& mSmartPtr<T>::operator=( mSmartPtr<T> &src) {
if (this != &src) {
if (rc->remove() == 0) {
delete data;
delete rc;
}
data = src.data;
rc = src.rc;
rc->add();
}
return *this;
}
#endif /* defined(__ProjectManager__mSharedPtr__) */
let's say my application contains the following classes:
class Base
{
protected:
...
public:
virtual ~Base() =0;
...
};
class Derived1 : public Base
{
protected:
...
public:
virtual ~Derived1() {}
...
};
class Derived2 : public Base
{
protected:
...
public:
virtual ~Derived2() {}
...
};
and I need store data at the following way:
int int main(int argc, char const *argv[])
{
std::vector<mSmartPtr<Base>> v;
mSmartPtr<Derived1> d1 = foo();
v.push_back(d1);
return 0;
}
I need to fix somehow the cast operator, but how? how do I get the base class in the dynamic cast?

#Guvante
Your code did not work , I modified it as follows but I don't know if will work well
template<class T>
mSmartPtr<T> mSmartPtr<T>::operator ()(mSmartPtr<T>& src) {
mSmartPtr<T> retVal(dynamic_cast<T*>(src.data));
retVal.rc = src.rc;
retVal.rc.Add();
return retVal;
}

I think there is a better alternative to this. Unless you have a different location where you need to be able to do this, you can avoid the headache by changing the way you create the object.
int main(int argc, char const *argv[])
{
std::vector<mSmartPtr<Base>> v;
mSmartPtr<Base> d1 = static_cast<Base*>(foo());
v.push_back(d1);
return 0;
}
Just avoid creating an mSmartPtr that is typed differently than your vector.

In your conversion method extract the underlying pointer and cast it then put it into the new smart pointer. Don't forget to copy the RefCount and ensure that your target class has a virtual destructor (so the correct one gets called no matter which smart pointer gets dispossed last).
I couldn't figure out how to define it externally but an inline definition worked.
//In the definition, replacing this line
//mSmartPtr<T> operator()(mSmartPtr&)
template<class Tdest>
operator mSmartPtr<Tdest>() {
mSmartPtr<Tdest> retVal(static_cast<Tdest*>(data));
retVal.rc = rc;
retVal.rc.Add();
return retVal;
}
In theory you could also add a version that takes a r-value if you are using C++11 but I think that would take a little work to do correctly so I avoided it.

Related

C++ Anyone know more about this kind of pointer?

I have a World class and a Entity class.
The World class creates new Entites and retuns a pointer to it.
If i use that pointer im never sure if that pointer is still pointing to a valid Entity but i also dont want to use a shared_ptr because the Entity wont get deleted until all shared_ptr are released. So after some time i cameup with this pointer:
#include <iostream>
#include <unordered_map>
template<class T>
class Pointer
{
public:
Pointer() :m_ptr(nullptr){}
Pointer(T*p) :m_ptr(p) { m_ptr->addPtr(this); }
~Pointer() { if(valid()) m_ptr->removePtr(this); }
Pointer(const Pointer &other) :m_ptr(other.m_ptr)
{
if(valid())
m_ptr->addPtr(this);
}
Pointer& operator=(const Pointer& other)
{
if (valid())
m_ptr->removePtr(this);
m_ptr = other.m_pObj;
if (valid())
m_ptr->addPtr(this);
return *this;
}
T* operator->() { return m_ptr; }
T* operator*() { return *m_ptr; }
T* get() { return m_ptr; }
bool valid() { return m_ptr != nullptr; }
private:
template<typename T>
friend class PointerCollector;
T * m_ptr;
};
template <class T>
class PointerCollector
{
public:
PointerCollector() = default;
virtual ~PointerCollector()
{
for (auto &x : m_ptrList)
{
(x.second)->m_ptr = nullptr;
}
}
private:
void addPtr(Pointer<T> *ptr)
{
m_ptrList[ptr] = ptr;
}
void removePtr(Pointer<T> *ptr)
{
m_ptrList.erase(ptr);
}
template<typename T>
friend class Pointer;
std::unordered_map<Pointer<T>*, Pointer<T>*> m_ptrList;
};
class Test : public PointerCollector<Test>
{
public:
Test() {}
~Test() = default;
int getVal() { return m_val; }
private:
int m_val = 100;
};
void func(Pointer<Test> ptr)
{
if (ptr.valid())
{
std::cout << ptr->getVal();
}
else
{
std::cout << "Invalid!\n";
}
}
int main()
{
Test* myTest = new Test();
Pointer<Test> myPtr(myTest);
Pointer<Test> myPtr2(myPtr);
delete myTest;
func(myPtr2);
getchar();
return 0;
}
the Test class will collect the pointers to it and invalidates them if the class gets deleted.
Now i wanted to ask if anyone knows a better implementation or more infomation about this kind of pointer.
I compiled and tested the above code in Visual Studio 2017
The answer is yes, this pattern has been used before by many people. You just created a poor (and broken, because there's at least one outright bug and several things that are sub-optimal) re-implementation of ::std::weak_ptr<T>. You should consider using it instead.

How to make variable type polymorphism work?

I have a template Node which returns data of type T.
template <class T> Node
{
public:
virtual const T& GetData() = 0;
};
And I want to have derived classes RefNode, and ValueNode that contain Pointers to data, and actual data. So that I can choose whether to work with a copy of data or to work on actual data in a node.
template<class T> class RefNode : public Node<T>
{
public:
RefNode(T *_data) : data(_data) { }
const T& GetData() { return *data; }
protected:
DataType *data;
};
template<class T> class ValueNode : public Node<T>
{
public:
ValueNode(const T&_data) : data(_data) { }
const T& GetData() { return data; }
protected:
T data;
};
I know that templates can't have virtual methods, but I just wanted to illustrate the effect that I wanted to get. The effect that I wanted to get is:
//for class Vector
Vector v, *c;
c = new Vector();
Node<Vector>* node = new RefNode<Vector>(c);
Node<Vector>* node2 = new ValueNode<Vector>(a);
node2->GetData(); //calls ValueNode<Vector>'s GetData();
node->GetData(); //calls RefNode<Vector>'s GetData();
Is there any way in C++ to achieve this kind of behaviour?
EDIT:
I would use GetData() like this:
Vector *vecarr[9];
Node<Vector>* nodes[10];
nodes[0] = new RefNode<Vector>(vecarr[0]);
nodes[1] = new ValueNode<Vector>(Vector(2,3)); //non reference vector
nodes[2] = new RefNode<Vector>(vecarr[1]);
nodes[3] = new RefNode<Vector>(vecarr[2]);
.....
void processPositionNodes(Node<Vector> **nodes, int n)
{
for(int i=0; i< n; i++) //iterate over all nodes
{
Vector vec = nodes[i]->GetData();
//do something with vec
}
}
I want to be able to change the type of data the Node contains, because I want to implement several graph algorithms dealing with different types of data, (Vectors, scalars..)
This code works just fine (there are some minor and unrelevant changes to your version):
#include <iostream>
using namespace std;
template <class T>
class Node
{
public:
virtual const T& GetData() = 0;
};
template<class T>
class RefNode : public Node<T>
{
public:
RefNode(T *_data) : data(_data) { *data = 5; }
const T& GetData() { return *data; }
protected:
T *data;
};
template<class T> class ValueNode : public Node<T>
{
public:
ValueNode(const T&_data) : data(_data) { data = 5; }
const T& GetData() { return data; }
protected:
T data;
};
int main(){
double data;
Node<double>* rn = new RefNode<double>(&data);
Node<double>* rv = new ValueNode<double>(data);
const double& a = rn->GetData();
const double& b = rv->GetData();
cout << a << '\t' << b << endl;
}
However, there are some potential issues with this code: lack of virtual destructor in class Node, lack of copy ctor, dtor, and operator= in class RefNode
As pointed out in the comments, templates can indeed have virtual functions. However this is not going to solve your problem. In fact, you would need those functions to have different return types.
This is a possible template-based solution to your problem, it might not be the most elegant but you (we) can work on this basis
#include <iostream>
using namespace std;
template <typename T, template<typename> class Accessor, template<typename> class Traits>
class Node{
public:
Node() : data(5.){}
typedef typename Traits<T>::type getType;
getType get(){
return static_cast<Accessor<T>*>(this)->implementation();
}
virtual ~Node(){}
protected:
T data;
};
template <typename T>
struct TraitsP{
typedef T* type;
};
template <typename T>
class PointerAccessor : public Node<T, PointerAccessor, TraitsP>{
public:
typename TraitsP<T>::type implementation(){
return &(Node<T, PointerAccessor, TraitsP>::data);
}
};
template <typename T>
struct TraitsD{
typedef T type;
};
template <typename T>
class DirectAccessor : public Node<T, DirectAccessor, TraitsD>{
public:
typename TraitsD<T>::type implementation(){
T ret = Node<T, DirectAccessor, TraitsD>::data;
return ret;
}
};
int main(){
auto np = new PointerAccessor<double>();
double* p = np->get();
cout << *p << endl;
auto np2 = new DirectAccessor<double>();
double d = np2->get();
cout << d << endl;
}
What might seem strange about this solution is PointerAccessor being derived by Node\<..., PointerAccessor, ...>. This is the so called Curiously Recurring Template Pattern (CRTP)

Call the cast operator of template base class within the derived class

I have a template class, called Cell, here the definition:
template <class T>
class OneCell
{
.....
}
I have a cast operator from Cell to T, here
virtual operator const T() const
{
.....
}
Now i have derived class, called DCell, here
template <class T>
class DCell : public Cell<T>
{
.....
}
I need to override the Cell's cast operator (insert a little if), but after I need to call the Cell's cast operator. In other methods it's should be something like
virtual operator const T() const
{
if (...)
{
return Cell<T>::operator const T;
}
else throw ...
}
but i got a compiler error
error: argument of type 'const int (Cell::)()const' does not match 'const int'
What can I do?
Thank you, and sorry about my poor English.
You are missing parentheses, so the compiler thought you were trying to return the member function, not call it.
return Cell<T>::operator const T();
You're not actually calling the operator:
return Cell<T>::operator const T();
Full code:
template <class T>
class OneCell
{
public:
virtual operator const T() const
{
return T();
}
};
template <class T>
class DCell : public OneCell<T>
{
public:
virtual operator const T() const
{
cout << "operator called";
return OneCell<T>::operator const T();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
DCell<int> x;
int y = (int)x;
}
Consider this code with the implementations of Cell and DCell:
#include <iostream>
#include <exception>
template<class T>
class Cell
{
protected:
T cnt;
public:
Cell(const T& cnt = T()) : cnt(cnt){}
virtual operator const T() const { return cnt; }
};
bool test_bool = true;
template<class T>
class DCell : public Cell<T>
{
public:
DCell(const T& cnt = T()) : Cell<T>(cnt){}
virtual operator const T() const
{
if(test_bool)
{
return Cell<T>::operator const T(); // Here you had Cell<T>::operator const T;
} else {
throw std::exception();
}
}
};
int main()
{
DCell<int> cell(5);
std::cout << static_cast<int>(cell) << "\n"; // prints 5 (and a new line)
return 0;
}
Don't make the operator virtual. Instead, delegate to a protected virtual helper function.
template <class T>
class Cell
{
public:
operator const T() const { return cvt_T(); }
protected:
virtual const T cvt_T() const;
};
template <class T>
class DCell : public Cell<T>
{
const T cvt_T() const
{
if (...)
{
return Cell<T>::cvt_T();
}
else throw ...
}
};
This and other good practices can be learned from GotW, here is the section on virtual architecture.

Dynamic Object in C++?

I realize that I'll most likely get a lot of "you shouldn't do that because..." answers and they are most welcome and I'll probably totally agree with your reasoning, but I'm curious as to whether this is possible (as I envision it).
Is it possible to define a type of dynamic/generic object in C++ where I can dynamically create properties that are stored and retrieved in a key/value type of system? Example:
MyType myObject;
std::string myStr("string1");
myObject.somethingIJustMadeUp = myStr;
Note that obviously, somethingIJustMadeUp is not actually a defined member of MyType but it would be defined dynamically. Then later I could do something like:
if(myObject.somethingIJustMadeUp != NULL);
or
if(myObject["somethingIJustMadeUp"]);
Believe me, I realize just how terrible this is, but I'm still curious as to whether it's possible and if it can be done in a way that minimizes it's terrible-ness.
C++Script is what you want!
Example:
#include <cppscript>
var script_main(var args)
{
var x = object();
x["abc"] = 10;
writeln(x["abc"]);
return 0;
}
and it's a valid C++.
You can do something very similar with std::map:
std::map<std::string, std::string> myObject;
myObject["somethingIJustMadeUp"] = myStr;
Now if you want generic value types, then you can use boost::any as:
std::map<std::string, boost::any> myObject;
myObject["somethingIJustMadeUp"] = myStr;
And you can also check if a value exists or not:
if(myObject.find ("somethingIJustMadeUp") != myObject.end())
std::cout << "Exists" << std::endl;
If you use boost::any, then you can know the actual type of value it holds, by calling .type() as:
if (myObject.find("Xyz") != myObject.end())
{
if(myObject["Xyz"].type() == typeid(std::string))
{
std::string value = boost::any_cast<std::string>(myObject["Xyz"]);
std::cout <<"Stored value is string = " << value << std::endl;
}
}
This also shows how you can use boost::any_cast to get the value stored in object of boost::any type.
This can be a solution, using RTTI polymorphism
#include <map>
#include <memory>
#include <iostream>
#include <stdexcept>
namespace dynamic
{
template<class T, class E>
T& enforce(T& z, const E& e)
{ if(!z) throw e; return z; }
template<class T, class E>
const T& enforce(const T& z, const E& e)
{ if(!z) throw e; return z; }
template<class Derived>
class interface;
class aggregate;
//polymorphic uncopyable unmovable
class property
{
public:
property() :pagg() {}
property(const property&) =delete;
property& operator=(const property&) =delete;
virtual ~property() {} //just make it polymorphic
template<class Interface>
operator Interface*() const
{
if(!pagg) return 0;
return *pagg; //let the aggregate do the magic!
}
aggregate* get_aggregate() const { return pagg; }
private:
template<class Derived>
friend class interface;
friend class aggregate;
static unsigned gen_id()
{
static unsigned x=0;
return enforce(++x,std::overflow_error("too many ids"));
}
template<class T>
static unsigned id_of()
{ static unsigned z = gen_id(); return z; }
aggregate* pagg;
};
template<class Derived>
class interface: public property
{
public:
interface() {}
virtual ~interface() {}
unsigned id() const { return property::id_of<Derived>(); }
};
//sealed movable
class aggregate
{
public:
aggregate() {}
aggregate(const aggregate&) = delete;
aggregate& operator=(const aggregate&) = delete;
aggregate(aggregate&& s) :m(std::move(s.m)) {}
aggregate& operator=(aggregate&& s)
{ if(this!=&s) { m.clear(); std::swap(m, s.m); } return *this; }
template<class Interface>
aggregate& add_interface(interface<Interface>* pi)
{
m[pi->id()] = std::unique_ptr<property>(pi);
static_cast<property*>(pi)->pagg = this;
return *this;
}
template<class Inteface>
aggregate& remove_interface()
{ m.erase[property::id_of<Inteface>()]; return *this; }
void clear() { m.clear(); }
bool empty() const { return m.empty(); }
explicit operator bool() const { return empty(); }
template<class Interface>
operator Interface*() const
{
auto i = m.find(property::id_of<Interface>());
if(i==m.end()) return nullptr;
return dynamic_cast<Interface*>(i->second.get());
}
template<class Interface>
friend aggregate& operator<<(aggregate& s, interface<Interface>* pi)
{ return s.add_interface(pi); }
private:
typedef std::map<unsigned, std::unique_ptr<property> > map_t;
map_t m;
};
}
/// this is a sample on how it can workout
class interface_A: public dynamic::interface<interface_A>
{
public:
virtual void methodA1() =0;
virtual void methodA2() =0;
};
class impl_A1: public interface_A
{
public:
impl_A1() { std::cout<<"creating impl_A1["<<this<<"]"<<std::endl; }
virtual ~impl_A1() { std::cout<<"deleting impl_A1["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_A2: public interface_A
{
public:
impl_A2() { std::cout<<"creating impl_A2["<<this<<"]"<<std::endl; }
virtual ~impl_A2() { std::cout<<"deleting impl_A2["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
};
class interface_B: public dynamic::interface<interface_B>
{
public:
virtual void methodB1() =0;
virtual void methodB2() =0;
};
class impl_B1: public interface_B
{
public:
impl_B1() { std::cout<<"creating impl_B1["<<this<<"]"<<std::endl; }
virtual ~impl_B1() { std::cout<<"deleting impl_B1["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_B2: public interface_B
{
public:
impl_B2() { std::cout<<"creating impl_B2["<<this<<"]"<<std::endl; }
virtual ~impl_B2() { std::cout<<"deleting impl_B2["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
};
int main()
{
dynamic::aggregate agg1;
agg1 << new impl_A1 << new impl_B1;
dynamic::aggregate agg2;
agg2 << new impl_A2 << new impl_B2;
interface_A* pa = 0;
interface_B* pb = 0;
pa = agg1; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
agg2 = std::move(agg1);
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
return 0;
}
tested with MINGW4.6 on WinXPsp3
Yes it is terrible. :D
It had been done numerous times to different extents and success levels.
QT has Qobject from which everything related to them decends.
MFC has CObject from which eveything decends as does C++.net
I don't know if there is a way to make it less bad, I guess if you avoid multiple inheritance like the plague (which is otherwise a useful language feature) and reimplement the stdlib it would be better. But really if that is what you are after you are probably using the wrong language for the task.
Java and C# are much better suited to this style of programming.
#note if I have read your question wrong just delete this answer.
Check out Dynamic C++

Template Specialization over derived class

I don't know if it is possible, I checked on StackOverflow, I found a lot of stuff but nothing that really fit my problem (or I don't see the relation).
What I'd like to do is something like that:
class Bean
{
public:
Bean(){}
virtual ~Bean(){}
template <class T>
bool set_(T){return false;}
template <class T>
bool get_(T&){return false;}
};
template <class T>
class GenericBean: public Bean
{
protected:
T type;
};
class Prova : public GenericBean<int>
{
public:
Prova(){type = 0;}
template<int> bool set_(int value){ type=value;}
template<int> bool get_(int& value){value = type;}
};
I'd like to have on object like Prova, cast to Bean and get the specialized function,
What I want to do is something like this:
#include <vector>
#include "Bean.h"
using namespace std;
class VirtualMessage
{
public:
VirtualMessage(void){}
virtual ~VirtualMessage(void){}
template <class ReturnValue, class Item>
bool Get(ReturnValue & val)
{
for(size_t i = 0; i < m_vData.size(); i++)
{
if(m_vData[i].get_<ReturnValue>(val))
return true;
}
}
template <class Item, class Value>
bool Set(Value val)
{
Item bean;
if(bean.set_<Value>(val))
{
m_vData.push_back(bean);
return true;
}
return false;
}
protected:
vector<Bean> m_vData;
};
Main:
#include "VirtualMessage.h"
#include "Bean.h"
int main()
{
VirtualMessage msg;
if(msg.Set<Prova ,int>(4))
printf("Test 1 passed");
}
this code doesn't compile
Maybe nobody will use it, but I wrote something that fits my need. It's not perfect, I have to work on it but is a begin:
#define UNIQUE(T) unsigned int GetID(){return UniqueType<T>::id();}
struct UniqueTypeBase
{
static unsigned int _ids;
};
unsigned int UniqueTypeBase::_ids = 0;
template <class T>
struct UniqueType : public UniqueTypeBase
{
static const unsigned int id()
{
static unsigned int typeId = 0;
if (typeId == 0)
typeId = ++_ids;
return typeId;
}
};
template <class T>
class TemplateBean
{
public:
T m_tValue;
template<class T> set_(T){return false;}
template<class T> get_(T&){return false;}
bool set_(T value){ m_tValue = value; return true;}
bool get_(T& value) { value = m_tValue;return true;}
};
class Prova : public TemplateBean<int>
{
public:
UNIQUE(Prova)
Prova(){m_tValue = 0;}
};
class Prova2 : public TemplateBean<float>
{
public:
UNIQUE(Prova2)
Prova2(){m_tValue = 0;}
};
class VirtualMessage
{
public:
VirtualMessage(void){}
virtual ~VirtualMessage(void){}
template <class Item, class ReturnValue>
bool Get(ReturnValue & val)
{
Item a;
map<unsigned int, void*>::iterator it;
it = m_TagMap.find(a.GetID());
if(it != m_TagMap.end())
{
Item* pItem = reinterpret_cast<Item*>(it->second);
if(pItem->get_(val))
return true;
}
return false;
}
template <class Item, class Value>
bool Set(Value val)
{
Item* pBean = new Item();
if(pBean->set_(val))
{
m_TagMap[pBean->GetID()] = (void*)pBean;
return true;
}
return false;
}
protected:
map<unsigned int, void*> m_TagMap;
};
Test Main:
int main()
{
VirtualMessage msg;
if(msg.Set<Prova ,int>(4))
printf("Test 1 passed\n");
if(!msg.Set<Prova,float>(4.00))
printf("Test 2 succed\n");
if(msg.Set<Prova2,float>(4.00))
printf("Test 3 succed\n");
int a=0;
if(msg.Get<Prova>(a))
printf("%d = 4...if 4=4 test passed\n",a);
float b=0;
if(msg.Get<Prova2>(b))
printf("%f = 4...if 4=4 test passed\n",b);
getchar();
}
I think you misunderstood the use of templates.
Templates are blueprints to build classes or methods, that the compiler use to produce real classes and methods (which is called instantiation).
As such, they are purely a compile-time facility. Therefore, they cannot be virtual, and thus overloading a template method in a derived class does not mean what you expect. It hides the base class method when used from derived (statically) but you still call the base class method if you use a reference or pointer to the base class.
What you are trying to achieve is, unfortunately, impossible with templates: it requires a runtime check.
Furthermore, you are using a std::vector<Bean> which will not work as intended. Polymorphic types shall not be manipulated by values in C++, you need a std::vector< std::unique_ptr<Bean> > or boost::ptr_vector<Bean>...
I would recommend reading a good C++ primer before attempting the kind of task you have set yourself upon. You need a basic introduction to C++ paradigms... and gotchas. And there are a lot of gotchas.