Suvarna Garge (Editor)

Utility (C )

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

utility is a header file in the C++ Standard Library. This file has two key components:

Contents

  • rel_ops, a namespace containing set of templates which define default behavior for the relational operators !=, >, <=, and >= between objects of the same type, based on user-defined operators == and <.
  • pair, a container template which holds two member objects (first and second) of arbitrary type(s). Additionally, the header defines default relational operators for pairs which have both types in common.
  • rel_ops

    GCC′s implementation declares the rel_ops namespace (nested within namespace std) in the following manner:

    Consider the following declaration of class A, which defines equality and less-than operators for comparison against other objects of the same type:

    By invoking the rel_ops templates, one can assign a default meaning to the remaining relational operators. However, if a similar type-specific (i.e. non-template) operator exists in the current scope, even outside the class definition, the compiler will prefer it instead.

    One could of course declare the following in tandem with rel_ops, allowing the derivation of all relational operators from <:

    pair

    An object declared, for example, as std::pair<int, float> will contain two members, int first; and float second;, plus three constructor functions.

    The first (default) constructor initializes both members with the default values 0 and 0.0, whereas the second one accepts one parameter of each type. The third is a template copy-constructor which will accept any std::pair<_U1, _U2>, provided the types _U1 and _U2 are capable of implicit conversion to int and float respectively.

    GCC′s implementation defines the pair mechanism as follows.

    Additionally this header defines all six relational operators for pair instances with both types in common. These define a strict weak ordering for objects of type std::pair<_T1, _T2>, based on the first elements and then upon the second elements only when the first ones are equal.

    Additionally the header contains a template-function make_pair() which deduces its return type based on parameters:

    References

    Utility (C++) Wikipedia