3

我需要有效的方法来将不同类型的值(int、float、QString 或 std::string、bool)存储在像 QVariant 这样的“通用”容器之一中。

我想归档更少的内存使用。

我更喜欢不存储内部值类型的容器,因为它是开销。

我应该使用哪一个?

4

2 回答 2

3

boost::any可以保存任何类型的值,但是您必须知道它可以保存什么才能提取该值,并且它会在堆上为存储的值分配内存。

boost::variant另一方面,只能存储一组指定类型的值,并且您可以轻松找出它所包含的内容,sizeofofboost::variant将是sizeof它包含的最大值类型+存储值类型的一些额外内容,因为它不使用堆内存(除非使用递归变体)。

从内存使用的角度来看boost::variant可能更有效,因为它不使用堆内存。此外,boost::variant它更加类型安全boost::any,编译器可以在编译时为您找到更多错误。

于 2014-06-02T08:52:46.800 回答
-1

大约一年前,我遇到过类似的问题。我不记得是什么原因了,但我已经有了提升:任何。boost:any 确实存储了可用于以期望格式检索值的 typeid。

这是一个例子:

#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's double type: " << boost::any_cast<double>(value) << std::endl;
        else if(value.type() == typeid(int))
            std::cout << "it's int type: " << boost::any_cast<int>(value) << std::endl;
        else if(value.type() == typeid(std::string))
            std::cout << "it's string type: " << boost::any_cast<std::string>(value) << std::endl;
    }
    return 0;
}

希望这可以帮助!!

于 2014-06-02T07:51:48.997 回答