std.traits

Templates which extract information about types and symbols at compile time.

CategoryTemplates
Symbol Name traitsfullyQualifiedName mangledName moduleName packageName
Function traitsisFunction arity functionAttributes hasFunctionAttributes functionLinkage FunctionTypeOf isSafe isUnsafe isFinal ParameterDefaults ParameterIdentifierTuple ParameterStorageClassTuple Parameters ReturnType SetFunctionAttributes variadicFunctionStyle
Aggregate Type traitsBaseClassesTuple BaseTypeTuple classInstanceAlignment EnumMembers FieldNameTuple Fields hasAliasing hasElaborateAssign hasElaborateCopyConstructor hasElaborateDestructor hasElaborateMove hasIndirections hasMember hasStaticMember hasNested hasUnsharedAliasing InterfacesTuple isInnerClass isNested MemberFunctionsTuple RepresentationTypeTuple TemplateArgsOf TemplateOf TransitiveBaseTypeTuple
Type ConversionCommonType AllImplicitConversionTargets ImplicitConversionTargets CopyTypeQualifiers CopyConstness isAssignable isCovariantWith isImplicitlyConvertible isQualifierConvertible
Type ConstructorsInoutOf ConstOf SharedOf SharedInoutOf SharedConstOf SharedConstInoutOf ImmutableOf QualifierOf
Categories of typesallSameType ifTestable isType isAggregateType isArray isAssociativeArray isAutodecodableString isBasicType isBoolean isBuiltinType isCopyable isDynamicArray isEqualityComparable isFloatingPoint isIntegral isNarrowString isConvertibleToString isNumeric isOrderingComparable isPointer isScalarType isSigned isSIMDVector isSomeChar isSomeString isStaticArray isUnsigned
Type behavioursisAbstractClass isAbstractFunction isCallable isDelegate isExpressions isFinalClass isFinalFunction isFunctionPointer isInstanceOf isIterable isMutable isSomeFunction isTypeTuple
General TypesForeachType KeyType Largest mostNegative OriginalType PointerTarget Signed Unconst Unshared Unqual Unsigned ValueType Promoted
MisclvalueOf rvalueOf Select select
User-Defined AttributeshasUDA getUDAs getSymbolsByUDA

Members

Aliases

ConstOf
alias ConstOf(T) = const(T)
FieldTypeTuple
alias FieldTypeTuple = Fields

Alternate name for Fields, kept for legacy compatibility.

ImmutableOf
alias ImmutableOf(T) = immutable(T)
InoutOf
alias InoutOf(T) = inout(T)
KeyType
alias KeyType(V : V[K], K) = K

Get the Key type of an Associative Array.

ParameterDefaultValueTuple
alias ParameterDefaultValueTuple = ParameterDefaults

Alternate name for ParameterDefaults, kept for legacy compatibility.

ParameterTypeTuple
alias ParameterTypeTuple = Parameters

Alternate name for Parameters, kept for legacy compatibility.

PointerTarget
alias PointerTarget(T : T*) = T

Returns the target type of a pointer.

SharedConstInoutOf
alias SharedConstInoutOf(T) = shared(const(inout(T)))
SharedConstOf
alias SharedConstOf(T) = shared(const(T))
SharedInoutOf
alias SharedInoutOf(T) = shared(inout(T))
SharedOf
alias SharedOf(T) = shared(T)
TemplateArgsOf
alias TemplateArgsOf(T : Base!Args, alias Base, Args...) = Args

Returns a AliasSeq of the template arguments used to instantiate T.

TemplateArgsOf
alias TemplateArgsOf(alias T : Base!Args, alias Base, Args...) = Args

Returns a AliasSeq of the template arguments used to instantiate T.

TemplateOf
alias TemplateOf(T) = void
alias TemplateOf(T : Base!Args, alias Base, Args...) = Base

Returns an alias to the template that T is an instance of. It will return void if a symbol without a template is given.

TemplateOf
alias TemplateOf(alias T : Base!Args, alias Base, Args...) = Base

Returns an alias to the template that T is an instance of. It will return void if a symbol without a template is given.

TransitiveBaseTypeTuple
alias TransitiveBaseTypeTuple(T) = AliasSeq!(BaseClassesTuple!T, InterfacesTuple!T)

Get a AliasSeq of all base classes of T, in decreasing order, followed by T's interfaces. TransitiveBaseTypeTuple!Object yields the empty type tuple.

ValueType
alias ValueType(V : V[K], K) = V

Get the Value type of an Associative Array.

isExpressionTuple
alias isExpressionTuple = isExpressions

Alternate name for isExpressions, kept for legacy compatibility.

Enums

FunctionAttribute
enum FunctionAttribute

Returns the FunctionAttribute mask for function func.

ParameterStorageClass
enum ParameterStorageClass

Get a tuple of the storage classes of a function's parameters.

Variadic
enum Variadic

Determines what kind of variadic parameters function has.

fullyQualifiedName
eponymoustemplate fullyQualifiedName(T)
eponymoustemplate fullyQualifiedName(alias T)

* Get the fully qualified name of a type or a symbol. Can act as an intelligent type/symbol to string converter.

hasMember
eponymoustemplate hasMember(T, string name)

Yields true if and only if T is an aggregate that defines a symbol called name.

hasUDA
eponymoustemplate hasUDA(alias symbol, alias attribute)

Determine if a symbol has a given user-defined attribute.

ifTestable
eponymoustemplate ifTestable(T, alias pred = a => a)
isAbstractClass
eponymoustemplate isAbstractClass(alias S)

Detect whether S is an abstract class.

isAbstractFunction
eponymoustemplate isAbstractFunction(alias S)

Detect whether S is an abstract function.

isAssignable
eponymoustemplate isAssignable(Lhs, Rhs = Lhs)

Returns true iff a value of type Rhs can be assigned to a variable of type Lhs.

isCopyable
eponymoustemplate isCopyable(S)

Determines whether the type S can be copied. If a type cannot be copied, then code such as MyStruct x; auto y = x; will fail to compile. Copying for structs can be disabled by using @disable this(this).

isFinalClass
eponymoustemplate isFinalClass(alias S)

Detect whether S is a final class.

isFinalFunction
eponymoustemplate isFinalFunction(alias S)

Detect whether S is a final function.

isLvalueAssignable
eponymoustemplate isLvalueAssignable(Lhs, Rhs = Lhs)

Returns true iff an lvalue of type Rhs can be assigned to a variable of type Lhs.

isRvalueAssignable
eponymoustemplate isRvalueAssignable(Lhs, Rhs = Lhs)

Returns true iff an rvalue of type Rhs can be assigned to a variable of type Lhs.

isType
eponymoustemplate isType(alias X)

Detect whether X is a type. Analogous to is(X). This is useful when used in conjunction with other templates, e.g. allSatisfy!(isType, X).

isTypeTuple
eponymoustemplate isTypeTuple(T...)

Check whether the tuple T is a type tuple. A type tuple only contains types.

mangledName
eponymoustemplate mangledName(alias sth)

Returns the mangled name of symbol or type sth.

Functions

select
B select(A a, B b)

Select one of two functions to run via template parameter.

select
A select(A a, B b)

Select one of two functions to run via template parameter.

Properties

lvalueOf
T lvalueOf [@property getter]

Creates an lvalue or rvalue of type T for typeof(...) and __traits(compiles, ...) purposes. No actual value is returned.

rvalueOf
T rvalueOf [@property getter]

Creates an lvalue or rvalue of type T for typeof(...) and __traits(compiles, ...) purposes. No actual value is returned.

Templates

AllImplicitConversionTargets
template AllImplicitConversionTargets(T)
BaseClassesTuple
template BaseClassesTuple(T)

Get a AliasSeq of all base classes of this class, in decreasing order. Interfaces are not included. BaseClassesTuple!Object yields the empty type tuple.

BaseTypeTuple
template BaseTypeTuple(A)

Get a AliasSeq of the base class and base interfaces of this class or interface. BaseTypeTuple!Object returns the empty type tuple.

CommonType
template CommonType(T...)

Get the type that all types can be implicitly converted to. Useful e.g. in figuring out an array type from a bunch of initializing values. Returns void if passed an empty list, or if the types have no common type.

CopyConstness
template CopyConstness(FromType, ToType)

Returns the type of ToType with the "constness" of FromType. A type's constness refers to whether it is const, immutable, or inout. If FromType has no constness, the returned type will be the same as ToType.

CopyTypeQualifiers
template CopyTypeQualifiers(FromType, ToType)

Copies type qualifiers from FromType to ToType.

DeducedParameterType
template DeducedParameterType(T)

The parameter type deduced by IFTI when an expression of type T is passed as an argument to a template function.

EnumMembers
template EnumMembers(E)

Retrieves the members of an enumerated type enum E.

FieldNameTuple
template FieldNameTuple(T)

Get as an expression tuple the names of the fields of a struct, class, or union. This consists of the fields that take up memory space, excluding the hidden fields like the virtual function table pointer or a context pointer for nested types. Inherited fields (for classes) are not included. If T isn't a struct, class, interface or union, an expression tuple with an empty string is returned.

Fields
template Fields(T)

Get as a tuple the types of the fields of a struct, class, or union. This consists of the fields that take up memory space, excluding the hidden fields like the virtual function table pointer or a context pointer for nested types. If T isn't a struct, class, interface or union returns a tuple with one element T.

ForeachType
template ForeachType(T)

Returns the inferred type of the loop variable when a variable of type T is iterated over using a foreach loop with a single loop variable and automatically inferred return type. Note that this may not be the same as std.range.ElementType!Range in the case of narrow strings, or if T has both opApply and a range interface.

FunctionTypeOf
template FunctionTypeOf(alias func)

Get the function type from a callable object func, or from a function pointer/delegate type.

ImplicitConversionTargets
deprecated template ImplicitConversionTargets(T)
InterfacesTuple
template InterfacesTuple(T)
Largest
template Largest(T...)

Returns the largest type, i.e. T such that T.sizeof is the largest. If more than one type is of the same size, the leftmost argument of these in will be returned.

MemberFunctionsTuple
template MemberFunctionsTuple(C, string name)

Returns a tuple of non-static functions with the name name declared in the class or interface C. Covariant duplicates are shrunk into the most derived one.

OriginalType
template OriginalType(T)

Strips off all enums from type T.

ParameterDefaults
template ParameterDefaults(alias func)

Get, as a tuple, the default values of the parameters to a function symbol. If a parameter doesn't have the default value, void is returned instead.

ParameterIdentifierTuple
template ParameterIdentifierTuple(alias func)

Get, as a tuple, the identifiers of the parameters to a function symbol.

ParameterStorageClassTuple
template ParameterStorageClassTuple(alias func)

Get a tuple of the storage classes of a function's parameters.

Parameters
template Parameters(alias func)

Get, as a tuple, the types of the parameters to a function, a pointer to function, a delegate, a struct with an opCall, a pointer to a struct with an opCall, or a class with an opCall.

Promoted
template Promoted(T)

Get the type that a scalar type T will promote to in multi-term arithmetic expressions.

QualifierOf
template QualifierOf(T)

Gives a template that can be used to apply the same attributes that are on the given type T. E.g. passing inout shared int will return SharedInoutOf.

RepresentationTypeTuple
template RepresentationTypeTuple(T)

Get the primitive types of the fields of a struct or class, in topological order.

ReturnType
template ReturnType(alias func)

Get the type of the return value from a function, a pointer to function, a delegate, a struct with an opCall, a pointer to a struct with an opCall, or a class with an opCall. Please note that $(D_KEYWORD ref) is not part of a type, but the attribute of the function (see template functionAttributes).

Select
template Select(bool condition, T...)

Aliases itself to T[0] if the boolean condition is true and to T[1] otherwise.

SetFunctionAttributes
template SetFunctionAttributes(T, string linkage, uint attrs)

Constructs a new function or delegate type with the same basic signature as the given one, but different attributes (including linkage).

SetFunctionAttributes
template SetFunctionAttributes(T, string linkage, uint attrs)

Constructs a new function or delegate type with the same basic signature as the given one, but different attributes (including linkage).

Signed
template Signed(T)

Returns the corresponding signed type for T. T must be a numeric integral type, otherwise a compile-time error occurs.

Unconst
template Unconst(T)

Removes const, inout and immutable qualifiers, if any, from type T.

Unqual
template Unqual(T)

Removes all qualifiers, if any, from type T.

Unshared
template Unshared(T)

Removes shared qualifier, if any, from type T.

Unsigned
template Unsigned(T)
arity
template arity(alias func)

Returns the number of arguments of function func. arity is undefined for variadic functions.

classInstanceAlignment
template classInstanceAlignment(T)

Returns class instance alignment.

extractParameterStorageClassFlags
template extractParameterStorageClassFlags(Attribs...)

Convert the result of __traits(getParameterStorageClasses) to ParameterStorageClass enums.

functionAttributes
template functionAttributes(alias func)

Returns the FunctionAttribute mask for function func.

functionLinkage
template functionLinkage(alias func)

Determine the linkage attribute of the function.

getSymbolsByUDA
template getSymbolsByUDA(alias symbol, alias attribute)
getUDAs
template getUDAs(alias symbol, alias attribute)

Gets the matching user-defined attributes from the given symbol.

hasAliasing
template hasAliasing(T...)

Returns true if and only if T's representation includes at least one of the following:

  1. a raw pointer U* and U is not immutable;
  2. an array U[] and U is not immutable;
  3. a reference to a class or interface type C and C is not immutable.
  4. an associative array that is not immutable.
  5. a delegate.
hasElaborateAssign
template hasElaborateAssign(S)

True if S or any type directly embedded in the representation of S defines an elaborate assignment. Elaborate assignments are introduced by defining opAssign(typeof(this)) or opAssign(ref typeof(this)) for a struct or when there is a compiler-generated opAssign.

hasElaborateCopyConstructor
template hasElaborateCopyConstructor(S)

True if S or any type embedded directly in the representation of S defines an elaborate copy constructor. Elaborate copy constructors are introduced by defining this(this) for a struct.

hasElaborateDestructor
template hasElaborateDestructor(S)

True if S or any type directly embedded in the representation of S defines an elaborate destructor. Elaborate destructors are introduced by defining ~this() for a struct.

hasElaborateMove
template hasElaborateMove(S)

True if S or any type embedded directly in the representation of S defines elaborate move semantics. Elaborate move semantics are introduced by defining opPostMove(ref typeof(this)) for a struct.

hasFunctionAttributes
template hasFunctionAttributes(args...)

Checks whether a function has the given attributes attached.

hasIndirections
template hasIndirections(T)

Returns true if and only if T's representation includes at least one of the following:

  1. a raw pointer U*;
  2. an array U[];
  3. a reference to a class type C;
  4. an associative array;
  5. a delegate;
  6. a [context pointer]isNested.
hasNested
template hasNested(T)

Determines whether T or any of its representation types have a context pointer.

hasStaticMember
template hasStaticMember(T, string member)

Whether the symbol represented by the string, member, exists and is a static member of T.

hasUnsharedAliasing
template hasUnsharedAliasing(T...)

Returns true if and only if T's representation includes at least one of the following:

  1. a raw pointer U* and U is not immutable or shared;
  2. an array U[] and U is not immutable or shared;
  3. a reference to a class type C and C is not immutable or shared.
  4. an associative array that is not immutable or shared.
  5. a delegate that is not shared.
isAutodecodableString
template isAutodecodableString(T)

Detect whether type T is a string that will be autodecoded.

isCallable
template isCallable(alias callable)

Detect whether T is a callable object, which can be called with the function call operator $(LPAREN)...$(RPAREN).

isConvertibleToString
template isConvertibleToString(T)

Warning: This trait will be deprecated as soon as it is no longer used in Phobos. For a function parameter to safely accept a type that implicitly converts to string as a string, the conversion needs to happen at the callsite; otherwise, the conversion is done inside the function, and in many cases, that means that local memory is sliced (e.g. if a static array is passed to the function, then it's copied, and the resulting dynamic array will be a slice of a local variable). So, if the resulting string escapes the function, the string refers to invalid memory, and accessing it would mean accessing invalid memory. As such, the only safe way for a function to accept types that implicitly convert to string is for the implicit conversion to be done at the callsite, and that can only occur if the parameter is explicitly typed as an array, whereas using isConvertibleToString in a template constraint would result in the conversion being done inside the function. As such, isConvertibleToString is inherently unsafe and is going to be deprecated.

isCovariantWith
template isCovariantWith(F, G)

Determines whether the function type F is covariant with G, i.e., functions of the type F can override ones of the type G.

isDynamicArray
template isDynamicArray(T)

Detect whether type T is a dynamic array.

isExpressions
template isExpressions(T...)

Check whether the tuple T is an expression tuple. An expression tuple only contains expressions.

isFinal
template isFinal(alias X)

Detect whether X is a final method or class.

isFunction
template isFunction(alias X)

Detect whether symbol or type X is a function. This is different that finding if a symbol is callable or satisfying is(X == function), it finds specifically if the symbol represents a normal function declaration, i.e. not a delegate or a function pointer.

isInnerClass
template isInnerClass(T)

Determines whether T is a class nested inside another class and that T.outer is the implicit reference to the outer class (i.e. outer has not been used as a field or method name)

isInstanceOf
template isInstanceOf(alias S, alias T)

Returns true if T is an instance of the template S.

isIntegral
template isIntegral(T)

Detect whether T is a built-in integral type. Integral types are byte, ubyte, short, ushort, int, uint, long, ulong, cent, ucent, and enums with an integral type as its base type.

isNested
template isNested(T)

Determines whether T has its own context pointer. T must be either class, struct, or union.

isNestedFunction
template isNestedFunction(alias f)

Determines if f is a function that requires a context pointer.

isNumeric
template isNumeric(T)

Detect whether T is a built-in numeric type (integral or floating point).

isSafe
template isSafe(alias func)

true if func is @safe or @trusted.

isSomeChar
template isSomeChar(T)

Detect whether T is one of the built-in character types.

isUnsafe
template isUnsafe(alias func)

true if func is @system.

isUnsigned
template isUnsigned(T)

Detect whether T is a built-in unsigned numeric type.

moduleName
template moduleName(alias T)

Get the module name (including package) for the given symbol.

mostNegative
template mostNegative(T)

Returns the most negative value of the numeric type T.

packageName
template packageName(alias T)

Get the full package name for the given symbol.

variadicFunctionStyle
template variadicFunctionStyle(alias func)

Determines what kind of variadic parameters function has.

Variables

allSameType
enum bool allSameType(Ts...);
isAggregateType
enum bool isAggregateType(T);

Detect whether type T is an aggregate type.

isArray
enum bool isArray(T);

Detect whether type T is an array (static or dynamic; for associative arrays see isAssociativeArray).

isAssociativeArray
enum bool isAssociativeArray(T);

Detect whether T is an associative array type

isBasicType
enum bool isBasicType(T);

Detect whether T is a basic type (scalar type or void).

isBoolean
enum bool isBoolean(T);

Detect whether T is a built-in boolean type or enum of boolean base type.

isBuiltinType
enum bool isBuiltinType(T);

Detect whether type T is a builtin type.

isDelegate
enum bool isDelegate(alias T);

Detect whether symbol or type T is a delegate.

isEqualityComparable
enum bool isEqualityComparable(T);

Detects whether T is a comparable type. Basic types and structs and classes that implement opCmp are ordering comparable.

isFloatingPoint
enum bool isFloatingPoint(T);

Detect whether T is a built-in floating point type.

isFunctionPointer
enum bool isFunctionPointer(alias T);

Detect whether symbol or type T is a function pointer.

isImplicitlyConvertible
enum bool isImplicitlyConvertible(From, To);

Is From implicitly convertible to To?

isInstanceOf
enum bool isInstanceOf(alias S, T);

Returns true if T is an instance of the template S.

isIterable
enum bool isIterable(T);

Returns true if T can be iterated over using a foreach loop with a single loop variable of automatically inferred type, regardless of how the foreach loop is implemented. This includes ranges, structs/classes that define opApply with a single loop variable, and builtin dynamic, static and associative arrays.

isMutable
enum bool isMutable(T);

Returns true if T is not const or immutable. Note that isMutable is true for string, or immutable(char)[], because the 'head' is mutable.

isNarrowString
enum bool isNarrowString(T);

Detect whether type T is a narrow string.

isOrderingComparable
enum bool isOrderingComparable(T);

Detects whether T is a comparable type. Basic types and structs and classes that implement opCmp are ordering comparable.

isPointer
enum bool isPointer(T);

Detect whether type T is a pointer.

isQualifierConvertible
enum bool isQualifierConvertible(From, To);

Is From qualifier-convertible to To?

isSIMDVector
enum bool isSIMDVector(T);

Detect whether type T is a SIMD vector type.

isScalarType
enum bool isScalarType(T);

Detect whether T is a scalar type (a built-in numeric, character or boolean type).

isSigned
enum bool isSigned(T);

Detect whether T is a built-in signed numeric type.

isSomeFunction
enum bool isSomeFunction(alias T);

Detect whether symbol or type T is a function, a function pointer or a delegate.

isSomeString
enum bool isSomeString(T);

Detect whether T is one of the built-in string types.

isStaticArray
enum bool isStaticArray(T);

Detect whether type T is a static array.

Meta

Authors

Walter Bright, Tomasz Stachowiak (isExpressions), Andrei Alexandrescu, Shin Fujishiro, Robert Clipsham, David Nadlinger, Kenji Hara, Shoichi Kato