0

我正在尝试根据这个答案解决昨天在 SO 上提出的问题

我已修改此处给出的代码以使用std::any而不是void*. 我目前拥有的代码如下:

#include <iostream>
#include <map>
#include <vector>
#include <any>
#include <typeindex>
struct cStreet{};
struct cHouse{};
struct cComputer{};
struct cBook{};
class cPlayer
{
public:

    struct Properties
    {
        std::vector<cStreet*>    Streets;
        std::vector<cHouse*>     Houses;
        std::vector<cComputer*>  Computers;
        std::vector<cBook*>      Book;
    };
    
    cPlayer(std::string name) : m_name{name}{};
    ~cPlayer(){};
    std::string         m_name{};
    Properties          m_Properties;
    
    
    std::map<std::type_index, std::any> myMap{{typeid(cStreet*), m_Properties.Streets}, {typeid(cHouse*), m_Properties.Houses}, {typeid(cComputer*), m_Properties.Computers}, {typeid(cBook*), m_Properties.Book}};
    
    
    template<typename T> void buy(T& Arg);
    
};
template<typename T> void cPlayer::buy(T& Arg)
{
    std::cout << m_name.c_str() << " : Do you want buy this ?" <<typeid(Arg).name() << std::endl;
    //Todo: Decision (here yes)
    std::any_cast<std::vector<decltype(&Arg)>>(myMap.at(typeid(&Arg))).push_back(&Arg); //THIS DOESN'T ADD ELEMENTS INTO THE VECTORS BECAUSE STD::ANY HAS A COPY OF THE ORIGINAL VECTORS
    
    
}

int main()
{
    //create objects 
    cStreet S;
    cHouse H;
    cComputer C;
    cBook B;
    cPlayer c("anoop");
    
    //lets test our code
    c.buy(S);   
    c.buy(H);
    c.buy(C);
    c.buy(B);
    
}

问题是当我写

std::any_cast<std::vector<decltype(&Arg)>>(myMap.at(typeid(&Arg))).push_back(&Arg);

这不会将push_back元素添加到原始向量中,而是添加到原始向量中。

如何将元素添加到原始向量m_Properties.Streets等中m_Properties.Houses我尝试使用std::ref,但我无法使用std::ref.

4

1 回答 1

0

根据这个答案,重新定义你myMap的:

std::map<std::type_index, std::any> myMap{
  {typeid(cStreet*), std::ref(m_Properties.Streets)}, 
  {typeid(cHouse*), std::ref(m_Properties.Houses)}, 
  {typeid(cComputer*), std::ref(m_Properties.Computers)}, 
  {typeid(cBook*), std::ref(m_Properties.Book)}
};

然后根据访问原文转换any成对应的类型:reference_wrapperTvector

template<typename T> 
void cPlayer::buy(T& Arg) {
  // ...
  using mapped_type = std::reference_wrapper<std::vector<T*>>; 
  std::any_cast<mapped_type>(myMap.at(typeid(T*))).get().push_back(&Arg);
  // ...
}
于 2021-12-17T06:33:12.020 回答