代码之家  ›  专栏  ›  技术社区  ›  Tony The Lion

C++中的联合与非缺省可构造对象

  •  4
  • Tony The Lion  · 技术社区  · 14 年前

    我的程序中有一种情况,我需要做一些从字符串到各种类型的转换,显然结果只能是一种类型。所以我选择创建一个 union 并称之为变体:

    union variant
    {
        int v_int;
        float v_float;
        double v_double;
        long v_long;
        boost::gregorian::date v_date; // Compiler complains this object has a user-defined ctor and/or non-default ctor. 
    }; 
    

    我使用它如下:

    bool Convert(const std::string& str, variant& var)
    {
        StringConversion conv;
    
        if (conv.Convert(str, var.v_int))
            return true;
        else if (conv.Convert(str, var.v_long))
            return true;
        else if (conv.Convert(str, var.v_float))
            return true;
        else if (conv.Convert(str, var.v_double))
            return true;
        else if (conv.Convert(str, var.v_date))
            return true;
        else 
            return false;
    }
    

    然后我在这里使用这个函数:

    while (attrib_iterator != v_attributes.end())  //Iterate attributes of an XML Node
                {
                    //Go through all attributes & insert into qsevalues map
                    Values v;  // Struct with a string & boost::any
                    v.key = attrib_iterator->key; 
                    ///value needs to be converted to its proper type.
                    v.value = attrib_iterator->value;
                    variant var;
                    bool isConverted = Convert(attrib_iterator->value, var); //convert to a type, not just a string
                    nodesmap.insert(std::pair<std::string, Values>(nodename, v));
                    attrib_iterator++;
                }
    

    问题是如果我使用 struct 然后,它的用户将能够在其中坚持一个以上的价值,而这真的不是注定要发生的。但似乎我也不能使用工会,因为我不能把 boost::gregorian::date 物体在里面。如果有什么方法我可以用 联盟 ?

    3 回复  |  直到 12 年前
        1
  •  5
  •   Cătălin Pitiș    14 年前

    使用boost::variant或boost::any。当你不得不合并非豆荚时,联合不是一个解决方案。

        2
  •  1
  •   Martin v. Löwis    14 年前

    不要使用gregorian::date,而是存储一个greg_ymd结构,并使用year_month_day()方法将日期转换为ymd。

        3
  •  0
  •   Chris    14 年前

    你是说你不能把boost::gregorian::date放在union中,因为它是非POD类型的?C++0X放宽了这种限制。如果您得到gcc 4.6并使用-std=c++0x构建它,那么您可以将它放在一个联合体中。请看这里: http://en.wikipedia.org/wiki/C%2B%2B0x#Unrestricted_unions .

    推荐文章