CppWAMP
C++11 client library for the WAMP protocol
|
A wamp::Variant is a discriminated union container that represents a JSON value. It behaves similarly to a dynamically-typed Javascript variable. Its underlying type can change at runtime, depending on the actual values assigned to them. Variant
s play a central role in CppWAMP, as they are used to represent dynamic data exchanged with a WAMP peer.
Variant
s can hold any of the following value types:
Array
and Object
variants are recursive composites: their element values are also variants which can themselves be arrays or objects.
A default-constructed Variant
starts out being null:
A Variant
can also be constructed with an initial value:
The dynamic type of a Variant
can change at runtime via assignment:
Each Variant
stores its current dynamic type as a wamp::TypeId enumerator. The dynamic type can be checked with wamp::Variant::typeId() or wamp::Variant::is<T>(). In addition, operator bool
can be used to determine if a variant is null.
The isNumber non-member function can be used to check if a Variant
is currently a number (Int
, UInt
, or Real
). The isScalar non-member function checks if a variant is a boolean or a number:
Variant values can be accessed directly using Variant::as<T>(). If the variant does not match the target type, a wamp::error::Access exception is thrown.
For convenience, elements can be accessed directly from array variants, using the [] operator taking an integer index:
For convenience, members can be accessed directly from object variants, using the [] operator taking a string key:
Variant
s may also contain arbitrary binary objects. Such binary objects must be stored in wamp::Blob, which is simply a wrapper around std::vector<uint8_t>
.
When transmitted using JSON serialization, Blob
s are encoded as Base64 strings prefixed with a nul character. For MsgPack, they are encoded in bin
format.
Because variants can be null, they can be used to contain optional (i.e. nullable) values. The boolean conversion operator is useful for knowing if a variant is currently null:
The valueOr member function can be used to obtain a fallback value if a variant is null:
Sometimes, it's not possible to know what numeric type to expect from a WAMP peer. wamp::Variant::to lets you convert from any scalar type to a known destination type.
Variant
objects can be compared with each other, or with other values. For the comparison to be equal, both types must match. However, all numeric types are considered to be the same type for comparison purposes (this is to more closely match the behavior of the ===
operator in Javascript, where it does not distinguish between signed/unsigned or integer/floating-point numbers).
wamp::Variant, wamp::Array, and wamp::Object objects can be outputted to a std::ostream
:
Next: Connectors