Variant

优质
小牛编辑
130浏览
2023-12-01

头文件: "boost/variant.hpp"

通过单个头文件就包含了所有 Variant 库。

"boost/variant/variant_fwd.hpp"

包含了 variant 类模板的前向声明。

"boost/variant/variant.hpp"

包含了 variant 类模板的定义。

"boost/variant/apply_visitor.hpp"

包含了对 variant 应用访问者机制的功能。

"boost/variant/get.hpp"

包含了模板函数 get.

"boost/variant/bad_visit.hpp"

包含了异常类 bad_visit 的定义。

"boost/variant/static_visitor.hpp"

包含了 visitor 类模板的定义。

以下部分摘要包含了 variant 类模板中最重要的成员。其它功能,如访问者机制,类型安全的直接取回,还有更先进的特性,如通过类型列表创建类型组等等,在 "Usage" 节讨论。

namespace boost {
  template <typename T1,typename T2=unspecified, ...,
    typename TN=unspecified>
  class variant {
  public:

    variant();

    variant(const variant& other);

    template <typename T> variant(const T& operand);

    template <typename U1, typename U2, ..., typename UN>
      variant(const variant<U1, U2, ..., UN>& operand);

    ~variant();

    template <typename T> variant& operator=(const T& rhs);

    int which() const;
    bool empty() const;
    const std::type_info& type() const;

    bool operator==(const variant& rhs) const;
    bool operator<(const variant& rhs) const;
  };
}

成员函数

variant();

这个构造函数对 variant 的类型组中的第一个类型进行缺省构造。这意味着在声明 variant 类型时,第一个类型必须是可以被缺省构造的,或者 variant 类型本身不能被缺省构造。该构造函数传播任何从第一个类型的构造函数抛出的异常。

variant(const variant& other);

这个复制构造函数复制 other 的当前值,并传播任何从 other 的当前类型的复制构造函数抛出的异常。

template <typename T> variant(const T& operand);

这个构造函数从 operand 构造一个新的 variant 。operand 的类型 T, 必须可以转换为限定类型组中的某个类型。复制或转换 operand 时抛出的异常将被传播。

template <typename U1,typename U2,...,typename UN>
  variant(const variant<U1,U2,...,UN>& operand);

这个构造函数允许从另一个 variant 类型进行构造,后者的类型组为 U1, U2UN, 它们必须可以转换为 T1,T2TN (被构造的 variant 的类型组)。复制或转换 operand 时抛出的异常将被传播。

~variant();

销毁 variant, 并调用当前值的析构函数。注意,对于指针类型,不调用析构函数(销毁指针是无操作的)。析构函数不抛出异常。

template <typename T> variant& operator=(const T& rhs);

这个操作符放弃当前值,并赋予值 rhs. 类型 T 必须可以转换为 variant 的限定类型组中的某个类型。如果 T 正好是 variant 当前值的类型,rhs 被复制赋值给当前值;从 T 的赋值操作符抛出的异常将被传播。如果 variant 当前值的类型不是 T, 则当前值被替换为从类型 T 的(复制)构造函数所创建的值。从构造函数抛出的异常将被传播。这个函数还可能抛出 bad_alloc.

int which() const;

返回一个从零起计的索引,表示当前值类型在限定类型组中的位置。这个函数不会抛出异常。

bool empty() const;

这个函数永远返回 false, 因为一个 variant 永远不会为空。这个函数的存在是为了允许泛型代码把 variantboost::any 视为同一种类型来处理。这个函数不会抛出异常。

const std::type_info& type() const;

返回当前值的 type_info 。这个函数不会抛出异常。

bool operator==(const variant& rhs) const;

如果 *this and rhs 相等则返回 true ,即 which()==rhs.which()*this 的当前值与 rhs 根据当前值的类型的相等操作是相等的。这要求限定类型组中的所有类型都必须是可以进行等同性比较的(EqualityComparable)。当前值的类型的 operator== 抛出的任何异常将被传播。

bool operator<(const variant& rhs) const;

小于比较返回 which()&lt;rhs.which() 或者,如果该索引相等,则返回对 *this 的当前值与 rhs 调用 operator&lt; 所返回的结果。当前值的类型的 operator&lt; 抛出的任何异常将被传播。