首页 > 解决方案 > 通过基类指针访问派生类函数,无需动态转换

问题描述

我试图找到一种方法来通过基指针访问派生类的函数而无需动态转换。我已经尝试过这篇文章中建议的访问者模式,但它似乎不适用于模板派生类。这是我所拥有的:

#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;

}

我的最终目标是能够比较 Derived 类的两个实例的基础数据。有没有办法完成这样的任务?

标签: c++oopinheritance

解决方案


推荐阅读