C ++拥有一种可以指向/引用已分配在堆栈上的不同类型的数据的映射的现代方式

问题描述 投票:0回答:1

使用原始指针,可以像这样实现:

#include <iostream>
#include <string>
#include <map>

using namespace std;

class base {
public:
    virtual ~base(){}
};

class derived1 : public base {
public:
    virtual ~derived1(){}
    derived1(const int& other) : val(other) {}
    int val;
};

class derived2 : public base {
public:
    virtual ~derived2(){}
    derived2(const float& other) : val(other) {}
    float val;
};


int main()
{
    derived1 dataA = 4;
    derived2 dataB = 3.0f;

    std::map<std::string, base*> mapOfPointersToData; //Needs to be a pointer because it can be of type deribed1 or derived2. Cant be smart as pointing to stack memory
    mapOfPointersToData["dataA"] = &dataA;
    mapOfPointersToData["dataB"] = &dataB;

    base* result = mapOfPointersToData["dataA"];

    std::cout << dynamic_cast<derived1*>(result)->val << std::endl;

    return 0;
}

这有效,但是有人告诉我,应该避免使用原始指针,而建议使用智能指针或引用。

对象永远不能为null,因此使用引用很有意义。我们可以通过使用变体来解决映射只能存储一种数据类型的问题:

int main()
{
    derived1 dataA = 4;
    derived2 dataB = 3.0f;

    std::map<std::string, std::variant<derived1, derived2>&> mapOfPointersToData; //Cant be constructed
    mapOfPointersToData["dataA"] = dataA;
    mapOfPointersToData["dataB"] = dataB;

    auto result = mapOfPointersToData["dataA"];

    std::cout << std::get<derived1>(result).val << std::endl;

    return 0;
}

但是这给出了错误

error: value-initialization of reference type ‘std::variant<derived1, derived2>&

那么存储对堆栈数据的引用的最佳方法是什么,该引用可以是不同的类型?

谢谢。

c++ reference smart-pointers
1个回答
1
投票

这有效,但是有人告诉我,应该避免使用原始指针,而建议使用智能指针或引用。

© www.soinside.com 2019 - 2024. All rights reserved.