我正在尝试根据这个答案解决昨天在 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
.