0

I am trying to find a way to access a function of the derived class through the base pointer without dynamic casting. I have tried the visitor pattern as suggested in this post, but it seems like it does not work for templated Derived class. Here is what I have:

#include <iostream>
#include <memory>

class Base
{
    public:
        virtual print() = 0;
};

template<class T>
class Derived final : public Base
{
    private:
        T value;

    public:
        Derived() = default;

        explicit Derived(const T& data) : value{data} {}

        T get_value () {return this->value;}   

        void print() {std::cout << value << std::endl;}

        ~Derived() {}
};


int main()
{
    std::shared_ptr<Base> ptr_one = std::make_shared<Derived<int>>(3);
    std::shared_ptr<Base> ptr_two = std::make_shared<Derived<int>>(3);

    auto value = ptr_one->get_value(); // This will cause an error.
    auto value_2 = ptr_two->get_value() // This will cause an error.

    std::cout << value == value_2 << std::endl; // This is my final goal. Being able to compare the underlying data.

    return 0;

}

My final goal is being able to compare the underlying data of two instances of the Derived class. Is there any way to achieve such task?

Songg Tùng
  • 139
  • 8
  • `static_cast(ptr_one.get())` maybe? – πάντα ῥεῖ Dec 06 '20 at 09:21
  • I don't think it would work as Derive is a template class? I think we would need to know the type of the Derived class to be able to cast it like that? – Songg Tùng Dec 06 '20 at 09:23
  • It should work for template classes as well: `static_cast*>(ptr_one.get())` – πάντα ῥεῖ Dec 06 '20 at 09:25
  • 2
    So why is `get_value` not part of the base interface? Or better, you could add a virtual `operator==`. There's always the option of [CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern), but that seems overkill for this situation. – JHBonarius Dec 06 '20 at 09:25
  • @πάνταῥεῖ But that requires the type to be known beforehand. If we have 2 vectors of base class pointer, we can't compare its element since the vector can contain the Derived class with any type of T. – Songg Tùng Dec 06 '20 at 09:33
  • @JHBonarius `get_value` is not a part of the base interface because the return type of the function depends on the template type T. But the idea of adding a virtual `operator==` seems possible, I'll try that. Thank you. – Songg Tùng Dec 06 '20 at 09:38
  • 1
    _@SonggTùng_ What @JHBonarius said, is the logical consequence: Add `Derived` as a template parameter of `Base`, and do the static cast there. That's what's called a CRTP. – πάντα ῥεῖ Dec 06 '20 at 09:41

0 Answers0