c++ - 通过基类指针访问派生类函数,无需动态转换
问题描述
我试图找到一种方法来通过基指针访问派生类的函数而无需动态转换。我已经尝试过这篇文章中建议的访问者模式,但它似乎不适用于模板派生类。这是我所拥有的:
#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 类的两个实例的基础数据。有没有办法完成这样的任务?
解决方案
推荐阅读
- oracle-apex - Oracle Apex 中间表插入
- oracle - Oracle PL/SQL 匿名块在修改为过程后停止工作
- openssl - 使用应用程序打包 OpenSSL
- chart.js - Chartjs 中 xAxes 的错误显示
- dart - 收听 ModalBottomSheet 关闭
- javascript - 如何为这些嵌套的 HTML 列表正确生成数据结构
- python - 使用数据框进行 Python 复杂操作
- elasticsearch - 不了解 _id 在 ES 上的行为
- c++ - Constexpr 替代放置 new 以使内存中的对象未初始化?
- php - php 在 Mac OS 上超时