QVariant vs boost :: any vs boost :: variant

I need an efficient way to store values ​​of different types (int, float, QString or std :: string, bool) in one of the "common" containers, such as QVariant.

I want to archive less memory usage.

I prefer a container that does not retain the type of internal value, because it is an overhead.

Which should i use?

+3
source share
2 answers

boost::any can contain values ​​of any type, but you should know what it can hold in order to be able to retrieve the value, and it allocates memory on the heap for the stored value.

boost::variant, , , , , sizeof of boost::variant sizeof + , ( ).

boost::variant , . , boost::variant , boost::any, .

+3

. , : . boost: , .

:

#include <iostream>
#include <boost/any.hpp>
#include <string>

int main()
{
    boost::any value;

    for(int i=0; i < 3; i++)
    {
        switch (i)
        {
        case 0:
            value = (double) 8.05;
            break;
        case 1:
            value = (int) 1;
            break;
        case 2:
            //std::string str = "Hello any world!";
            //value = str;
            value = std::string("Hello any world!");
            break;
        }

        if(value.type() == typeid(double))
            std::cout << "it double type: " << boost::any_cast<double>(value) << std::endl;
        else if(value.type() == typeid(int))
            std::cout << "it int type: " << boost::any_cast<int>(value) << std::endl;
        else if(value.type() == typeid(std::string))
            std::cout << "it string type: " << boost::any_cast<std::string>(value) << std::endl;
    }
    return 0;
}

, !

-1

All Articles