View source code
Display the source code in std/typecons.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Module std.typecons

This module implements a variety of type constructors, i.e., templates that allow construction of new, useful general-purpose types.

Category Functions
Tuple isTuple Tuple tuple reverse
Flags BitFlags isBitFlagEnum Flag No Yes
Memory allocation RefCounted refCounted RefCountedAutoInitialize scoped Unique
Code generation AutoImplement BlackHole generateAssertTrap generateEmptyFunction WhiteHole
Nullable Nullable nullable NullableRef nullableRef
Proxies Proxy rebindable Rebindable ReplaceType unwrap wrap
Types alignForSize Ternary Typedef TypedefType UnqualRef

Example

// value tuples
alias Coord = Tuple!(int, "x", int, "y", int, "z");
Coord c;
c[1] = 1;       // access by index
c.z = 1;        // access by given name
writeln(c); // Coord(0, 1, 1)

// names can be omitted
alias DicEntry = Tuple!(string, string);

// tuples can also be constructed on instantiation
writeln(tuple(2, 3, 4)[1]); // 3
// construction on instantiation works with names too
writeln(tuple!("x", "y", "z")(2, 3, 4).y); // 3

// Rebindable references to const and immutable objects
{
    class Widget { void foo() const @safe {} }
    const w1 = new Widget, w2 = new Widget;
    w1.foo();
    // w1 = w2 would not work; can't rebind const object
    auto r = Rebindable!(const Widget)(w1);
    // invoke method as if r were a Widget object
    r.foo();
    // rebind r to refer to another object
    r = w2;
}

Functions

NameDescription
alignForSize() Order the provided members to minimize size while preserving alignment. Alignment is not always optimal for 80-bit reals, nor for structs declared as align(1).
nullable(t) Defines a value paired with a distinctive "null" state that denotes the absence of a value. If default constructed, a Nullable!T object starts in the null state. Assigning it renders it non-null. Calling nullify can nullify it again.
nullable(t) Just like Nullable!T, except that the null state is defined as a particular value. For example, Nullable!(uint, uint.max) is an uint that sets aside the value uint.max to denote a null state. Nullable!(T, nullValue) is more storage-efficient than Nullable!T because it does not need to store an extra bool.
nullableRef(t) Just like Nullable!T, except that the object refers to a value sitting elsewhere in memory. This makes assignments overwrite the initially assigned value. Internally NullableRef!T only stores a pointer to T (i.e., Nullable!T.sizeof == (T*).sizeof).
rebindable(obj) Convenience function for creating a Rebindable using automatic type inference.
rebindable(obj) This function simply returns the Rebindable object passed in. It's useful in generic programming cases when a given object may be either a regular class or a Rebindable.
refCounted(val) Initializes a RefCounted with val. The template parameter T of RefCounted is inferred from val. This function can be used to move non-copyable values to the heap. It also disables the autoInit option of RefCounted.
reverse(t) Creates a copy of a Tuple with its fields in reverse order.

Classes

NameDescription
AutoImplement AutoImplement automatically implements (by default) all abstract member functions in the class or interface Base in specified way.

Structs

NameDescription
BitFlags A typesafe structure for storing combinations of enum values.
No Convenience names that allow using e.g. Yes.encryption instead of Flag!"encryption".yes and No.encryption instead of Flag!"encryption".no.
Nullable Defines a value paired with a distinctive "null" state that denotes the absence of a value. If default constructed, a Nullable!T object starts in the null state. Assigning it renders it non-null. Calling nullify can nullify it again.
Nullable Just like Nullable!T, except that the null state is defined as a particular value. For example, Nullable!(uint, uint.max) is an uint that sets aside the value uint.max to denote a null state. Nullable!(T, nullValue) is more storage-efficient than Nullable!T because it does not need to store an extra bool.
NullableRef Just like Nullable!T, except that the object refers to a value sitting elsewhere in memory. This makes assignments overwrite the initially assigned value. Internally NullableRef!T only stores a pointer to T (i.e., Nullable!T.sizeof == (T*).sizeof).
RefCounted Defines a reference-counted object containing a T value as payload.
Ternary Ternary type with three truth values:
Tuple Tuple of values, for example Tuple!(int, string) is a record that stores an int and a string. Tuple can be used to bundle values together, notably when returning multiple values from a function. If obj is a Tuple, the individual members are accessible with the syntax obj[0] for the first field, obj[1] for the second, and so on.
Typedef Typedef allows the creation of a unique type which is based on an existing type. Unlike the alias feature, Typedef ensures the two types are not considered as equals.
Unique Encapsulates unique ownership of a resource.
UnqualRef Similar to Rebindable!(T) but strips all qualifiers from the reference as opposed to just constness / immutability. Primary intended use case is with shared (having thread-local reference to shared class data)
Yes Convenience names that allow using e.g. Yes.encryption instead of Flag!"encryption".yes and No.encryption instead of Flag!"encryption".no.

Enums

NameDescription
Flag Defines a simple, self-documenting yes/no flag. This makes it easy for APIs to define functions accepting flags without resorting to bool, which is opaque in calls, and without needing to define an enumerated type separately. Using Flag!"Name" instead of bool makes the flag's meaning visible in calls. Each yes/no flag has its own type, which makes confusions and mix-ups impossible.
RefCountedAutoInitialize Options regarding auto-initialization of a RefCounted object (see the definition of RefCounted below).

Templates

NameDescription
apply Unpacks the content of a Nullable, performs an operation and packs it again. Does nothing if isNull.
Proxy Creates a proxy for the value a that will forward all operations while disabling implicit conversions. The aliased item a must be an lvalue. This is useful for creating a new type from the "base" type (though this is not a subtype-supertype relationship; the new type is not related to the old type in any way, by design).
scoped Allocates a class object right inside the current scope, therefore avoiding the overhead of new. This facility is unsafe; it is the responsibility of the user to not escape a reference to the object outside the scope.
tuple Constructs a Tuple object instantiated and initialized according to the given arguments.
unwrap Supports structural based typesafe conversion.
wrap Supports structural based typesafe conversion.

Manifest constants

NameTypeDescription
generateAssertTrap Predefined how-policies for AutoImplement. These templates are also used by BlackHole and WhiteHole, respectively.
generateEmptyFunction Predefined how-policies for AutoImplement. These templates are also used by BlackHole and WhiteHole, respectively.
isBitFlagEnum Detect whether an enum is of integral type and has only "flag" values (i.e. values with a bit count of exactly 1). Additionally, a zero value is allowed for compatibility with enums including a "None" value.
isTuple Returns true if and only if T is an instance of Tuple.

Aliases

NameTypeDescription
BlackHole AutoImplement!(Base,generateEmptyFunction,isAbstractFunction) BlackHole!Base is a subclass of Base which automatically implements all abstract member functions in Base as do-nothing functions. Each auto-implemented function just returns the default value of the return type without doing anything.
Rebindable const(ElementEncodingType!T)[] Rebindable!(T) is a simple, efficient wrapper that behaves just like an object of type T, except that you can reassign it to refer to another object. For completeness, Rebindable!(T) aliases itself away to T if T is a non-const object type.
ReplaceType ReplaceTypeUnless!(false_,From,To,T) Replaces all occurrences of From into To, in one or more types T. For example, ReplaceType!(int, uint, Tuple!(int, float)[string]) yields Tuple!(uint, float)[string]. The types in which replacement is performed may be arbitrarily complex, including qualifiers, built-in type constructors (pointers, arrays, associative arrays, functions, and delegates), and template instantiations; replacement proceeds transitively through the type definition. However, member types in structs or classes are not replaced because there are no ways to express the types resulting after replacement.
ReplaceTypeUnless T[0] Like ReplaceType, but does not perform replacement in types for which pred evaluates to true.
TypedefType Arg Get the underlying type which a Typedef wraps. If T is not a Typedef it will alias itself to T.
unwrap unwrap!(Unqual!Target) Supports structural based typesafe conversion.
WhiteHole AutoImplement!(Base,generateAssertTrap,isAbstractFunction) WhiteHole!Base is a subclass of Base which automatically implements all abstract member functions as functions that always fail. These functions simply throw an Error and never return. Whitehole is useful for trapping the use of class member functions that haven't been implemented.
wrap wrap!(staticMap!(Unqual,Targets)) Supports structural based typesafe conversion.

Authors

Andrei Alexandrescu, Bartosz Milewski, Don Clugston, Shin Fujishiro, Kenji Hara

License

Boost License 1.0.