Answer the question
In order to leave comments, you need to log in
How to implement a downcast to a template?
There is a class Base :
class Base
{
public:
Base *pointer = nullptr;
virtual void add(Base *element) = 0;
virtual void print() const = 0;
};
template <typename T>
class Element : public Base
{
public:
Element(T value) : value(value) { }
virtual void add(Base *element) override
{
}
virtual void print() const override
{
std::cout << value << std::endl;
}
private:
T value = 0;
};
int main()
{
Base *s = new Element <short> (1);
Base *i = new Element <int> (2);
Base *ll = new Element <long long> (4);
ll->add(s);
ll->add(i);
ll->print();
delete s;
delete i;
delete ll;
return 0;
}
#include <iostream>
#include <typeinfo>
class Base
{
public:
Base *pointer = nullptr;
virtual void add(Base *element) = 0;
virtual void print() const = 0;
template <typename> friend class Element;
private:
virtual const std::type_info& getType() const = 0;
};
template <typename T>
class Element : public Base
{
public:
Element(T value) : value(value) { }
virtual void add(Base *element) override
{
const std::type_info &type = element->getType();
if (type == typeid(short))
{
value += dynamic_cast <Element <short> *> (element)->value;
}
else if (type == typeid(int))
{
value += dynamic_cast <Element <int> *> (element)->value;
}
else if (type == typeid(long long))
{
value += dynamic_cast <Element <long long> *> (element)->value;
}
}
virtual void print() const override
{
std::cout << value << std::endl;
}
template <typename> friend class Element;
private:
T value = 0;
virtual const std::type_info& getType() const override
{
return typeid(T);
}
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question