The task of the following nature: You need a dynamic array that can take data of any type, for example, like vector.push_back, but any type. I need to serialize the data into this very array, which can take any data into itself, like an array.

I need this in order not to constantly create an array like this: [CLANG] char buffer [1024]; WriteInt4 (buffer, 50) WriteString (buffer, "hello")

foo (buffer.str (), buffer.lenght) [/ CLANG] And the data before calling foo will be this way (data in this order, you do not need to flip): 00 00 00 32 48 65 6c 6c 6f 00

Actually, how to be? I heard that there is std :: any, but I have no idea whether this is what I'm trying to find. boost I do not want to use.

I've also seen such code, it seems to be what you need, but it is inconvenient (not advertising): qaru.site/questions/7005490/possibility-of-store-object-type-for-stdany

How to be? I need a container that supports data output, as an array, and so that this array is filled in the order in which I will be pushing data into it.

  • Just in case: You understand that this qaru , to which you referred, simply automatically translates content from English SO? stackoverflow.com/questions/47705978/… - HolyBlackCat 11:12 pm
  • Do you really need to store any data types in an array? Can it make a wrapper over std::vector<unsigned char> with an overloaded / patterned push_back that will serialize the transferred objects to an internal vector, or will it not work? - HolyBlackCat
  • I don't know guys, I'm not C ++ at all, I just need to create a data stream and stuff it into an array, but I don't want to use the standard char array [size]. Is there a more comfortable and faster option? - Dan

1 answer 1

 std::vector<std::any> vector_of_any_object; vector_of_any_object.push_back(std::string("String object")); vector_of_any_object.push_back(5); vector_of_any_object.push_back(MySuperObject()); for (const auto& obj : vector_of_any_object) { const std::type_info& type = obj.type(); if (type == typeid(std::string)) { std::string& string_ref = std::any_cast<std::string&>(obj); string_ref = "new string"; // заменить текст в строке, которая хранится в vector_of_any_object } else if (type == typeid(int)) { } ... } 

PS If C ++ 17 is not available, then use boost :: any, if you don’t want to drag a boost, then pull the implementation of boost :: any to yourself, it is not big.

  • I do not need to pull data out of it, I just need to push and transfer right away. How to clean this vector after send? - Dan
  • By the way, which method will be faster? Use vector or standard static array? I understand that a regular array is faster and data is not required to be cleared, but I’m interested in how much the vector yields to a regular array - Dan
  • @ Dan Where to go? If over the network, then in any case you need the serializer of the objects in the byte sequence, then std :: any is not needed, since You can add to std :: vector <char> right away. - ffk