I am attempting to call a templated function on the value but I want to call the templated version of the function that is from the potentially derived type. It is being determined that the type is "Dog" during the typeid but any attempt to cast is coming up short. How can I call the derived types templated DoSomething function?
About the example 1. The DoSomething function is templated even though the value is not used in this example as I made a small example 2. It is not always knowthat the Array parameter will be an Animal
#include <iostream>
using namespace std;
template<typename Type>
struct Array {
Type Data[2];
template<typename StuffType>
void DoStuff(StuffType stuff) {
cout << "Data[0](typeid): " << typeid(*Data[0]).name() << endl;
cout << "Data[1](typeid): " << typeid(*Data[1]).name() << endl;
Data[0]->DoSomething(stuff); // "Animal is doing something"
Data[1]->DoSomething(stuff); // "Dog is doing something"
auto data1cast = reinterpret_cast<decltype(Data[1])>(Data[1]);
cout << "data1cast(typeid): " << typeid(*data1cast).name() << endl; // data1cast(typeid): class Dog
(*data1cast).DoSomething(stuff); // "Animal is doing something"
((Dog*)Data[1])->DoSomething(stuff); // "Dog is doing something"
}
};
struct Animal {
virtual ~Animal() = default;
template<typename StuffType>
void DoSomething(StuffType stuff) {
cout << "Animal is doing something" << endl;
}
};
struct Dog : Animal {
template<typename StuffType>
void DoSomething(StuffType stuff) {
cout << "Dog is doing something" << endl;
}
};
int main(void) {
Array<Animal*> arr;
arr.Data[0] = new Animal();
arr.Data[1] = new Dog();
arr.DoStuff(1);
system("PAUSE");
return 0;
}
Output
Data[0](typeid): struct Animal
Data[1](typeid): struct Dog
Animal is doing something
Animal is doing something
data1cast(typeid): struct Dog
Animal is doing something
Dog is doing something
Aucun commentaire:
Enregistrer un commentaire