std.traits
Source: std/traits.d
- template MutableOf(T)
- Add specific qualifier to the given type T.
- template InoutOf(T)
- Add specific qualifier to the given type T.
- template ConstOf(T)
- ditto.
- template SharedOf(T)
- ditto.
- template SharedInoutOf(T)
- ditto.
- template SharedConstOf(T)
- ditto.
- template ImmutableOf(T)
- ditto.
- template packageName(alias T)
- Get the full package name for the given symbol.Examples:
import std.traits; static assert(packageName!packageName == "std");
- template moduleName(alias T)
- Get the module name (including package) for the given symbol.Examples:
import std.traits; static assert(moduleName!moduleName == "std.traits");
- template fullyQualifiedName(T...) if (T.length == 1)
- Get the fully qualified name of a type or a symbol. Can act as an intelligent type/symbol to string converter.
Example:
module myModule; struct MyStruct {} static assert(fullyQualifiedName!(const MyStruct[]) == "const(myModule.MyStruct[])");
Examples:static assert(fullyQualifiedName!fullyQualifiedName == "std.traits.fullyQualifiedName");
- template ReturnType(func...) if (func.length == 1 && isCallable!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 ref is not part of a type, but the attribute of the function (see template functionAttributes).Examples:
int foo(); ReturnType!foo x; // x is declared as int
- template Parameters(func...) if (func.length == 1 && isCallable!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.Examples:
int foo(int, long); void bar(Parameters!foo); // declares void bar(int, long); void abc(Parameters!foo[1]); // declares void abc(long);
- alias ParameterTypeTuple = Parameters(func...) if (func.length == 1 && isCallable!func);
- Alternate name for Parameters, kept for legacy compatibility.
- template arity(alias func) if (isCallable!func && variadicFunctionStyle!func == Variadic.no)
-
Examples:
void foo(){} static assert(arity!foo==0); void bar(uint){} static assert(arity!bar==1); void variadicFoo(uint...){} static assert(__traits(compiles,arity!variadicFoo)==false);
- enum ParameterStorageClass: uint;
template ParameterStorageClassTuple(func...) if (func.length == 1 && isCallable!func) - Returns a tuple consisting of the storage classes of the parameters of a function func.Examples:
alias STC = ParameterStorageClass; // shorten the enum name void func(ref int ctx, out real result, real param) { } alias pstc = ParameterStorageClassTuple!func; static assert(pstc.length == 3); // three parameters static assert(pstc[0] == STC.ref_); static assert(pstc[1] == STC.out_); static assert(pstc[2] == STC.none);
- template ParameterIdentifierTuple(func...) if (func.length == 1 && isCallable!func)
- Get, as a tuple, the identifiers of the parameters to a function symbol.Examples:
int foo(int num, string name, int); static assert([ParameterIdentifierTuple!foo] == ["num", "name", ""]);
- template ParameterDefaults(func...) if (func.length == 1 && isCallable!func)
- Get, as a tuple, the default value of the parameters to a function symbol. If a parameter doesn't have the default value, void is returned instead.Examples:
int foo(int num, string name = "hello", int[] = [1,2,3]); static assert(is(ParameterDefaults!foo[0] == void)); static assert( ParameterDefaults!foo[1] == "hello"); static assert( ParameterDefaults!foo[2] == [1,2,3]);
- alias ParameterDefaultValueTuple = ParameterDefaults(func...) if (func.length == 1 && isCallable!func);
- Alternate name for ParameterDefaults, kept for legacy compatibility.
- enum FunctionAttribute: uint;
template functionAttributes(func...) if (func.length == 1 && isCallable!func) - Returns the attributes attached to a function func.Examples:
import std.traits : functionAttributes, FunctionAttribute; alias FA = FunctionAttribute; // shorten the enum name real func(real x) pure nothrow @safe { return x; } static assert(functionAttributes!func & FA.pure_); static assert(functionAttributes!func & FA.safe); static assert(!(functionAttributes!func & FA.trusted)); // not @trusted
- template isSafe(alias func) if (isCallable!func)
- true if func is @safe or @trusted.Examples:
@safe int add(int a, int b) {return a+b;} @trusted int sub(int a, int b) {return a-b;} @system int mul(int a, int b) {return a*b;} static assert( isSafe!add); static assert( isSafe!sub); static assert(!isSafe!mul);
- enum isUnsafe(alias func);
- true if func is @system.Examples:
@safe int add(int a, int b) {return a+b;} @trusted int sub(int a, int b) {return a-b;} @system int mul(int a, int b) {return a*b;} static assert(!isUnsafe!add); static assert(!isUnsafe!sub); static assert( isUnsafe!mul);
- template areAllSafe(funcs...) if (funcs.length > 0)
- Deprecated. It's badly named and provides redundant functionality. It was also badly broken prior to 2.060 (bug# 8362), so any code which uses it probably needs to be changed anyway. Please use allSatisfy(isSafe, ...) instead. This will be removed in June 2015.true all functions are isSafe. Example
@safe int add(int a, int b) {return a+b;} @trusted int sub(int a, int b) {return a-b;} @system int mul(int a, int b) {return a*b;} static assert( areAllSafe!(add, add)); static assert( areAllSafe!(add, sub)); static assert(!areAllSafe!(sub, mul));
- template functionLinkage(func...) if (func.length == 1 && isCallable!func)
- Returns the calling convention of function as a string.Examples:
extern(D) void Dfunc() {} extern(C) void Cfunc() {} static assert(functionLinkage!Dfunc == "D"); static assert(functionLinkage!Cfunc == "C"); string a = functionLinkage!Dfunc; assert(a == "D"); auto fp = &Cfunc; string b = functionLinkage!fp; assert(b == "C");
- enum Variadic: int;
template variadicFunctionStyle(func...) if (func.length == 1 && isCallable!func) - Determines what kind of variadic parameters function has.Examples:
void func() {} static assert(variadicFunctionStyle!func == Variadic.no); extern(C) int printf(in char*, ...); static assert(variadicFunctionStyle!printf == Variadic.c);
- template FunctionTypeOf(func...) if (func.length == 1 && isCallable!func)
- Get the function type from a callable object func.Using builtin typeof on a property function yields the types of the property value, not of the property function itself. Still, FunctionTypeOf is able to obtain function types of properties.
Note: Do not confuse function types with function pointer types; function types are usually used for compile-time reflection purposes.
Examples:class C { int value() @property { return 0; } } static assert(is( typeof(C.value) == int )); static assert(is( FunctionTypeOf!(C.value) == function ));
- template SetFunctionAttributes(T, string linkage, uint attrs) if (isFunctionPointer!T || isDelegate!T)
template SetFunctionAttributes(T, string linkage, uint attrs) if (is(T == function)) - Constructs a new function or delegate type with the same basic signature as the given one, but different attributes (including linkage).This is especially useful for adding/removing attributes to/from types in generic code, where the actual type name cannot be spelt out.Parameters:
T The base type. linkage The desired linkage of the result type. attrs The desired FunctionAttributes of the result type. Examples:alias ExternC(T) = SetFunctionAttributes!(T, "C", functionAttributes!T); auto assumePure(T)(T t) if (isFunctionPointer!T || isDelegate!T) { enum attrs = functionAttributes!T | FunctionAttribute.pure_; return cast(SetFunctionAttributes!(T, functionLinkage!T, attrs)) t; }
- template isNested(T) if (is(T == class) || is(T == struct) || is(T == union))
- Determines whether T has its own context pointer. T must be either class, struct, or union.Examples:
static struct S { } static assert(!isNested!S); int i; struct NestedStruct { void f() { ++i; } } static assert(isNested!NestedStruct);
- template hasNested(T)
- Determines whether T or any of its representation types have a context pointer.Examples:
static struct S { } int i; struct NS { void f() { ++i; } } static assert(!hasNested!(S[2])); static assert(hasNested!(NS[2]));
- 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, or union returns a tuple with one element T.Examples:
struct S { int x; float y; } static assert(is(Fields!S == TypeTuple!(int, float)));
- alias FieldTypeTuple = Fields(T);
- 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. If T isn't a struct, class, or union returns an expression tuple with an empty string.Examples:
struct S { int x; float y; } static assert(FieldNameTuple!S == TypeTuple!("x", "y")); static assert(FieldNameTuple!int == TypeTuple!"");
- template RepresentationTypeTuple(T)
- Get the primitive types of the fields of a struct or class, in topological order.Examples:
struct S1 { int a; float b; } struct S2 { char[] a; union { S1 b; S1 * c; } } alias R = RepresentationTypeTuple!S2; assert(R.length == 4 && is(R[0] == char[]) && is(R[1] == int) && is(R[2] == float) && is(R[3] == S1*));
- template hasAliasing(T...)
- Returns true if and only if T's representation includes at least one of the following:
- a raw pointer U* and U is not immutable;
- an array U[] and U is not immutable;
- a reference to a class or interface type C and C is not immutable.
- an associative array that is not immutable.
- a delegate.
Examples:struct S1 { int a; Object b; } struct S2 { string a; } struct S3 { int a; immutable Object b; } struct S4 { float[3] vals; } static assert( hasAliasing!S1); static assert(!hasAliasing!S2); static assert(!hasAliasing!S3); static assert(!hasAliasing!S4);
- template hasIndirections(T)
- Returns true if and only if T's representation includes at least one of the following:
- a raw pointer U*;
- an array U[];
- a reference to a class type C.
- an associative array.
- a delegate.
Examples:static assert( hasIndirections!(int[string])); static assert( hasIndirections!(void delegate())); static assert( hasIndirections!(void delegate() immutable)); static assert( hasIndirections!(immutable(void delegate()))); static assert( hasIndirections!(immutable(void delegate() immutable))); static assert(!hasIndirections!(void function())); static assert( hasIndirections!(void*[1])); static assert(!hasIndirections!(byte[1]));
- template hasUnsharedAliasing(T...)
- Returns true if and only if T's representation includes at least one of the following:
- a raw pointer U* and U is not immutable or shared;
- an array U[] and U is not immutable or shared;
- a reference to a class type C and C is not immutable or shared.
- an associative array that is not immutable or shared.
- a delegate that is not shared.
Examples:struct S1 { int a; Object b; } struct S2 { string a; } struct S3 { int a; immutable Object b; } static assert( hasUnsharedAliasing!S1); static assert(!hasUnsharedAliasing!S2); static assert(!hasUnsharedAliasing!S3); struct S4 { int a; shared Object b; } struct S5 { char[] a; } struct S6 { shared char[] b; } struct S7 { float[3] vals; } static assert(!hasUnsharedAliasing!S4); static assert( hasUnsharedAliasing!S5); static assert(!hasUnsharedAliasing!S6); static assert(!hasUnsharedAliasing!S7);
- 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.Classes and unions never have elaborate copy constructors.Examples:
static assert(!hasElaborateCopyConstructor!int); static struct S1 { } static struct S2 { this(this) {} } static struct S3 { S2 field; } static struct S4 { S3[1] field; } static struct S5 { S3[] field; } static struct S6 { S3[0] field; } static struct S7 { @disable this(); S3 field; } static assert(!hasElaborateCopyConstructor!S1); static assert( hasElaborateCopyConstructor!S2); static assert( hasElaborateCopyConstructor!(immutable S2)); static assert( hasElaborateCopyConstructor!S3); static assert( hasElaborateCopyConstructor!(S3[1])); static assert(!hasElaborateCopyConstructor!(S3[0])); static assert( hasElaborateCopyConstructor!S4); static assert(!hasElaborateCopyConstructor!S5); static assert(!hasElaborateCopyConstructor!S6); static assert( hasElaborateCopyConstructor!S7);
- 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.A type S gets compiler-generated opAssign in case it has an elaborate copy constructor or elaborate destructor. Classes and unions never have elaborate assignments.
Note: Structs with (possibly nested) postblit operator(s) will have a hidden yet elaborate compiler generated assignment operator (unless explicitly disabled).
Examples:static assert(!hasElaborateAssign!int); static struct S { void opAssign(S) {} } static assert( hasElaborateAssign!S); static assert(!hasElaborateAssign!(const(S))); static struct S1 { void opAssign(ref S1) {} } static struct S2 { void opAssign(int) {} } static struct S3 { S s; } static assert( hasElaborateAssign!S1); static assert(!hasElaborateAssign!S2); static assert( hasElaborateAssign!S3); static assert( hasElaborateAssign!(S3[1])); static assert(!hasElaborateAssign!(S3[0]));
- 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.Classes and unions never have elaborate destructors, even though classes may define ~this().Examples:
static assert(!hasElaborateDestructor!int); static struct S1 { } static struct S2 { ~this() {} } static struct S3 { S2 field; } static struct S4 { S3[1] field; } static struct S5 { S3[] field; } static struct S6 { S3[0] field; } static struct S7 { @disable this(); S3 field; } static assert(!hasElaborateDestructor!S1); static assert( hasElaborateDestructor!S2); static assert( hasElaborateDestructor!(immutable S2)); static assert( hasElaborateDestructor!S3); static assert( hasElaborateDestructor!(S3[1])); static assert(!hasElaborateDestructor!(S3[0])); static assert( hasElaborateDestructor!S4); static assert(!hasElaborateDestructor!S5); static assert(!hasElaborateDestructor!S6); static assert( hasElaborateDestructor!S7);
- enum hasMember(T, string name);
- Yields true if and only if T is an aggregate that defines a symbol called name.Examples:
static assert(!hasMember!(int, "blah")); struct S1 { int blah; } struct S2 { int blah(){ return 0; } } class C1 { int blah; } class C2 { int blah(){ return 0; } } static assert(hasMember!(S1, "blah")); static assert(hasMember!(S2, "blah")); static assert(hasMember!(C1, "blah")); static assert(hasMember!(C2, "blah"));
- template EnumMembers(E) if (is(E == enum))
- Retrieves the members of an enumerated type enum E.Parameters:
E An enumerated type. E may have duplicated values. Returns:Static tuple composed of the members of the enumerated type E. The members are arranged in the same order as declared in E.Note: An enum can have multiple members which have the same value. If you want to use EnumMembers to e.g. generate switch cases at compile-time, you should use the std.typetuple.NoDuplicates template to avoid generating duplicate switch cases.
Note: Returned values are strictly typed with E. Thus, the following code does not work without the explicit cast:
enum E : int { a, b, c } int[] abc = cast(int[]) [ EnumMembers!E ];
Cast is not necessary if the type of the variable is inferred. See the example below.Examples:Creating an array of enumerated values:enum Sqrts : real { one = 1, two = 1.41421, three = 1.73205, } auto sqrts = [ EnumMembers!Sqrts ]; assert(sqrts == [ Sqrts.one, Sqrts.two, Sqrts.three ]);
A generic function rank(v) in the following example uses this template for finding a member e in an enumerated type E.// Returns i if e is the i-th enumerator of E. size_t rank(E)(E e) if (is(E == enum)) { foreach (i, member; EnumMembers!E) { if (e == member) return i; } assert(0, "Not an enum member"); } enum Mode { read = 1, write = 2, map = 4, } assert(rank(Mode.read ) == 0); assert(rank(Mode.write) == 1); assert(rank(Mode.map ) == 2);
- template BaseTypeTuple(A)
- Get a TypeTuple of the base class and base interfaces of this class or interface. BaseTypeTuple!Object returns the empty type tuple.Examples:
interface I1 { } interface I2 { } interface I12 : I1, I2 { } static assert(is(BaseTypeTuple!I12 == TypeTuple!(I1, I2))); interface I3 : I1 { } interface I123 : I1, I2, I3 { } static assert(is(BaseTypeTuple!I123 == TypeTuple!(I1, I2, I3)));
- template BaseClassesTuple(T) if (is(T == class))
- Get a TypeTuple of all base classes of this class, in decreasing order. Interfaces are not included. BaseClassesTuple!Object yields the empty type tuple.Examples:
class C1 { } class C2 : C1 { } class C3 : C2 { } static assert(!BaseClassesTuple!Object.length); static assert(is(BaseClassesTuple!C1 == TypeTuple!(Object))); static assert(is(BaseClassesTuple!C2 == TypeTuple!(C1, Object))); static assert(is(BaseClassesTuple!C3 == TypeTuple!(C2, C1, Object)));
- template InterfacesTuple(T)
- template TransitiveBaseTypeTuple(T)
- Get a TypeTuple of all base classes of T, in decreasing order, followed by T's interfaces. TransitiveBaseTypeTuple!Object yields the empty type tuple.Examples:
interface J1 {} interface J2 {} class B1 {} class B2 : B1, J1, J2 {} class B3 : B2, J1 {} alias TL = TransitiveBaseTypeTuple!B3; assert(TL.length == 5); assert(is (TL[0] == B2)); assert(is (TL[1] == B1)); assert(is (TL[2] == Object)); assert(is (TL[3] == J1)); assert(is (TL[4] == J2)); assert(TransitiveBaseTypeTuple!Object.length == 0);
- template MemberFunctionsTuple(C, string name) if (is(C == class) || is(C == interface))
- 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.Examples:
interface I { I foo(); } class B { real foo(real v) { return v; } } class C : B, I { override C foo() { return this; } // covariant overriding of I.foo() } alias foos = MemberFunctionsTuple!(C, "foo"); static assert(foos.length == 2); static assert(__traits(isSame, foos[0], C.foo)); static assert(__traits(isSame, foos[1], B.foo));
- template TemplateOf(alias T : Base!Args, alias Base, Args...)
template TemplateOf(T : Base!Args, alias Base, Args...) - Returns an alias to the template that T is an instance of.Examples:
struct Foo(T, U) {} static assert(__traits(isSame, TemplateOf!(Foo!(int, real)), Foo));
- template TemplateArgsOf(alias T : Base!Args, alias Base, Args...)
template TemplateArgsOf(T : Base!Args, alias Base, Args...) - Returns a TypeTuple of the template arguments used to instantiate T.Examples:
struct Foo(T, U) {} static assert(is(TemplateArgsOf!(Foo!(int, real)) == TypeTuple!(int, real)));
- template classInstanceAlignment(T) if (is(T == class))
- Returns class instance alignment.Examples:
class A { byte b; } class B { long l; } // As class instance always has a hidden pointer static assert(classInstanceAlignment!A == (void*).alignof); static assert(classInstanceAlignment!B == long.alignof);
- 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.Examples:
alias X = CommonType!(int, long, short); assert(is(X == long)); alias Y = CommonType!(int, char[], short); assert(is(Y == void));
- template ImplicitConversionTargets(T)
- Returns a tuple with all possible target types of an implicit conversion of a value of type T.
- enum bool isImplicitlyConvertible(From, To);
- Is From implicitly convertible to To?
- enum isAssignable(Lhs, Rhs = Lhs);
- Returns true iff a value of type Rhs can be assigned to a variable of type Lhs.isAssignable returns whether both an lvalue and rvalue can be assigned. If you omit Rhs, isAssignable will check identity assignable of Lhs.Examples:
static assert( isAssignable!(long, int)); static assert(!isAssignable!(int, long)); static assert( isAssignable!(const(char)[], string)); static assert(!isAssignable!(string, char[])); // int is assignable to int static assert( isAssignable!int); // immutable int is not assignable to immutable int static assert(!isAssignable!(immutable int));
- template isCovariantWith(F, G) if (is(F == function) && is(G == function))
- Determines whether the function type F is covariant with G, i.e., functions of the type F can override ones of the type G.Examples:
interface I { I clone(); } interface J { J clone(); } class C : I { override C clone() // covariant overriding of I.clone() { return new C; } } // C.clone() can override I.clone(), indeed. static assert(isCovariantWith!(typeof(C.clone), typeof(I.clone))); // C.clone() can't override J.clone(); the return type C is not implicitly // convertible to J. static assert(!isCovariantWith!(typeof(C.clone), typeof(J.clone)));
- @property T rvalueOf(T)(inout __InoutWorkaroundStruct = __InoutWorkaroundStruct.init);
@property ref T lvalueOf(T)(inout __InoutWorkaroundStruct = __InoutWorkaroundStruct.init); - Creates an lvalue or rvalue of type T for typeof(...) and _traits(compiles, ...) purposes. No actual value is returned.
Note: Trying to use returned value will result in a "Symbol Undefined" error at link time.
Examples:// Note that `f` doesn't have to be implemented // as is isn't called. int f(int); bool f(ref int); static assert(is(typeof(f(rvalueOf!int)) == int)); static assert(is(typeof(f(lvalueOf!int)) == bool)); int i = rvalueOf!int; // error, no actual value is returned
- enum bool isBoolean(T);
- Detect whether T is a built-in boolean type.Examples:
static assert( isBoolean!bool); enum EB : bool { a = true } static assert( isBoolean!EB); static assert(!isBoolean!(SubTypeOf!bool));
- enum bool isIntegral(T);
- Detect whether T is a built-in integral type. Types bool, char, wchar, and dchar are not considered integral.
- enum bool isFloatingPoint(T);
- Detect whether T is a built-in floating point type.
- enum bool isNumeric(T);
- Detect whether T is a built-in numeric type (integral or floating point).
- enum bool isScalarType(T);
- Detect whether T is a scalar type (a built-in numeric, character or boolean type).Examples:
static assert(!isScalarType!void); static assert( isScalarType!(immutable(int))); static assert( isScalarType!(shared(float))); static assert( isScalarType!(shared(const bool))); static assert( isScalarType!(const(dchar)));
- enum bool isBasicType(T);
- Detect whether T is a basic type (scalar type or void).Examples:
static assert(isBasicType!void); static assert(isBasicType!(immutable(int))); static assert(isBasicType!(shared(float))); static assert(isBasicType!(shared(const bool))); static assert(isBasicType!(const(dchar)));
- enum bool isUnsigned(T);
- Detect whether T is a built-in unsigned numeric type.
- enum bool isSigned(T);
- Detect whether T is a built-in signed numeric type.
- enum bool isSomeChar(T);
- Detect whether T is one of the built-in character types.Examples:
static assert(!isSomeChar!int); static assert(!isSomeChar!byte); static assert(!isSomeChar!string); static assert(!isSomeChar!wstring); static assert(!isSomeChar!dstring); static assert(!isSomeChar!(char[4]));
- enum bool isSomeString(T);
- Detect whether T is one of the built-in string types.The built-in string types are Char[], where Char is any of char, wchar or dchar, with or without qualifiers. Static arrays of characters (like char[80]) are not considered built-in string types.Examples:
static assert(!isSomeString!int); static assert(!isSomeString!(int[])); static assert(!isSomeString!(byte[])); static assert(!isSomeString!(typeof(null))); static assert(!isSomeString!(char[4])); enum ES : string { a = "aaa", b = "bbb" } static assert( isSomeString!ES);
- enum bool isNarrowString(T);
- Detect whether type T is a narrow string.All arrays that use char, wchar, and their qualified versions are narrow strings. (Those include string and wstring).
- enum bool isAutodecodableString(T);
- Detect whether type T is a string that will be autodecoded.All arrays that use char, wchar, and their qualified versions are narrow strings. (Those include string and wstring). Aggregates that implicitly cast to narrow strings are included.Parameters:
T type to be tested Returns:true if T represents a string that is subject to autodecoding See Also: isNarrowStringExamples:static struct Stringish { string s; alias s this; } assert(isAutodecodableString!wstring); assert(isAutodecodableString!Stringish); assert(!isAutodecodableString!dstring);
- enum bool isStaticArray(T);
- Detect whether type T is a static array.Examples:
static assert(!isStaticArray!(const(int)[])); static assert(!isStaticArray!(immutable(int)[])); static assert(!isStaticArray!(const(int)[4][])); static assert(!isStaticArray!(int[])); static assert(!isStaticArray!(int[char])); static assert(!isStaticArray!(int[1][])); static assert(!isStaticArray!(int[int])); static assert(!isStaticArray!int);
- enum bool isDynamicArray(T);
- Detect whether type T is a dynamic array.
- enum bool isArray(T);
- Detect whether type T is an array (static or dynamic; for associative arrays see isAssociativeArray).
- enum bool isAssociativeArray(T);
- Detect whether T is an associative array type
- enum bool isBuiltinType(T);
- Detect whether type T is a builtin type.Examples:
class C; union U; struct S; interface I; static assert( isBuiltinType!void); static assert( isBuiltinType!string); static assert( isBuiltinType!(int[])); static assert( isBuiltinType!(C[string])); static assert(!isBuiltinType!C); static assert(!isBuiltinType!U); static assert(!isBuiltinType!S); static assert(!isBuiltinType!I); static assert(!isBuiltinType!(void delegate(int)));
- enum bool isSIMDVector(T);
- Detect whether type T is a SIMD vector type.
- enum bool isPointer(T);
- Detect whether type T is a pointer.
- template PointerTarget(T : T*)
- Returns the target type of a pointer.
- deprecated alias pointerTarget = PointerTarget(T : T*);
- Deprecated. Please use PointerTarget instead. This will be removed in June 2015.
- enum bool isAggregateType(T);
- Detect whether type T is an aggregate type.Examples:
class C; union U; struct S; interface I; static assert( isAggregateType!C); static assert( isAggregateType!U); static assert( isAggregateType!S); static assert( isAggregateType!I); static assert(!isAggregateType!void); static assert(!isAggregateType!string); static assert(!isAggregateType!(int[])); static assert(!isAggregateType!(C[string])); static assert(!isAggregateType!(void delegate(int)));
- 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.Examples:
struct OpApply { int opApply(int delegate(ref uint) dg) { assert(0); } } struct Range { @property uint front() { assert(0); } void popFront() { assert(0); } enum bool empty = false; } static assert( isIterable!(uint[])); static assert( isIterable!OpApply); static assert( isIterable!(uint[string])); static assert( isIterable!Range); static assert(!isIterable!uint);
- 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.Examples:
static assert( isMutable!int); static assert( isMutable!string); static assert( isMutable!(shared int)); static assert( isMutable!(shared const(int)[])); static assert(!isMutable!(const int)); static assert(!isMutable!(inout int)); static assert(!isMutable!(shared(const int))); static assert(!isMutable!(shared(inout int))); static assert(!isMutable!(immutable string));
- enum bool isInstanceOf(alias S, T);
- Returns true if T is an instance of the template S.Examples:
static struct Foo(T...) { } static struct Bar(T...) { } static struct Doo(T) { } static struct ABC(int x) { } static assert(isInstanceOf!(Foo, Foo!int)); static assert(!isInstanceOf!(Foo, Bar!int)); static assert(!isInstanceOf!(Foo, int)); static assert(isInstanceOf!(Doo, Doo!int)); static assert(isInstanceOf!(ABC, ABC!1)); static assert(!__traits(compiles, isInstanceOf!(Foo, Foo)));
- template isExpressions(T...)
- Check whether the tuple T is an expression tuple. An expression tuple only contains expressions.See Also:Examples:
static assert(isExpressions!(1, 2.0, "a")); static assert(!isExpressions!(int, double, string)); static assert(!isExpressions!(int, 2.0, "a"));
- alias isExpressionTuple = isExpressions(T...);
- Alternate name for isExpressions, kept for legacy compatibility.
- template isTypeTuple(T...)
- Check whether the tuple T is a type tuple. A type tuple only contains types.See Also:Examples:
static assert(isTypeTuple!(int, float, string)); static assert(!isTypeTuple!(1, 2.0, "a")); static assert(!isTypeTuple!(1, double, string));
- template isFunctionPointer(T...) if (T.length == 1)
- Detect whether symbol or type T is a function pointer.Examples:
static void foo() {} void bar() {} auto fpfoo = &foo; static assert( isFunctionPointer!fpfoo); static assert( isFunctionPointer!(void function())); auto dgbar = &bar; static assert(!isFunctionPointer!dgbar); static assert(!isFunctionPointer!(void delegate())); static assert(!isFunctionPointer!foo); static assert(!isFunctionPointer!bar); static assert( isFunctionPointer!((int a) {}));
- template isDelegate(T...) if (T.length == 1)
- Detect whether symbol or type T is a delegate.Examples:
static void sfunc() { } int x; void func() { x++; } int delegate() dg; assert(isDelegate!dg); assert(isDelegate!(int delegate())); assert(isDelegate!(typeof(&func))); int function() fp; assert(!isDelegate!fp); assert(!isDelegate!(int function())); assert(!isDelegate!(typeof(&sfunc)));
- template isSomeFunction(T...) if (T.length == 1)
- Detect whether symbol or type T is a function, a function pointer or a delegate.
- template isCallable(T...) if (T.length == 1)
- Detect whether T is a callable object, which can be called with the function call operator (...).Examples:
interface I { real value() @property; } struct S { static int opCall(int) { return 0; } } class C { int opCall(int) { return 0; } } auto c = new C; static assert( isCallable!c); static assert( isCallable!S); static assert( isCallable!(c.opCall)); static assert( isCallable!(I.value)); static assert( isCallable!((int a) { return a; })); static assert(!isCallable!I);
- template isAbstractFunction(T...) if (T.length == 1)
- Detect whether T is a an abstract function.
- template isFinalFunction(T...) if (T.length == 1)
- Detect whether T is a a final function.Examples:
struct S { void bar() { } } final class FC { void foo(); } class C { void bar() { } final void foo(); } static assert(!isFinalFunction!(S.bar)); static assert( isFinalFunction!(FC.foo)); static assert(!isFinalFunction!(C.bar)); static assert( isFinalFunction!(C.foo));
- enum isNestedFunction(alias f);
- Determines whether function f requires a context pointer.
- template isAbstractClass(T...) if (T.length == 1)
- Detect whether T is a an abstract class.Examples:
struct S { } class C { } abstract class AC { } static assert(!isAbstractClass!S); static assert(!isAbstractClass!C); static assert( isAbstractClass!AC);
- template isFinalClass(T...) if (T.length == 1)
- Detect whether T is a a final class.Examples:
class C { } abstract class AC { } final class FC1 : C { } final class FC2 { } static assert(!isFinalClass!C); static assert(!isFinalClass!AC); static assert( isFinalClass!FC1); static assert( isFinalClass!FC2);
- template Unqual(T)
- Removes all qualifiers, if any, from type T.Examples:
static assert(is(Unqual!int == int)); static assert(is(Unqual!(const int) == int)); static assert(is(Unqual!(immutable int) == int)); static assert(is(Unqual!(shared int) == int)); static assert(is(Unqual!(shared(const int)) == int));
- template CopyTypeQualifiers(FromType, ToType)
- Copies type qualifiers from FromType to ToType.Supported type qualifiers:
- const
- inout
- immutable
- shared
Examples:static assert(is(CopyTypeQualifiers!(inout const real, int) == inout const int));
- template CopyConstness(FromType, ToType)
- Returns the type of Target with the "constness" of Source. A type's refers to whether it is const, immutable, or inout. If source has no constness, the returned type will be the same as Target.Examples:
const(int) i; CopyConstness!(typeof(i), float) f; assert( is(typeof(f) == const float)); CopyConstness!(char, uint) u; assert( is(typeof(u) == uint)); //The 'shared' qualifier will not be copied assert(!is(CopyConstness!(shared bool, int) == shared int)); //But the constness will be assert( is(CopyConstness!(shared const real, double) == const double)); //Careful, const(int)[] is a mutable array of const(int) alias MutT = CopyConstness!(const(int)[], int); assert(!is(MutT == const(int))); //Okay, const(int[]) applies to array and contained ints alias CstT = CopyConstness!(const(int[]), int); assert( is(CstT == const(int)));
- 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.Examples:
static assert(is(ForeachType!(uint[]) == uint)); static assert(is(ForeachType!string == immutable(char))); static assert(is(ForeachType!(string[string]) == string)); static assert(is(ForeachType!(inout(int)[]) == inout(int)));
- template OriginalType(T)
- Strips off all enums from type T.Examples:
enum E : real { a } enum F : E { a = E.a } alias G = const(F); static assert(is(OriginalType!E == real)); static assert(is(OriginalType!F == real)); static assert(is(OriginalType!G == const real));
- template KeyType(V : V[K], K)
- Get the Key type of an Associative Array.Examples:
import std.traits; alias Hash = int[string]; static assert(is(KeyType!Hash == string)); static assert(is(ValueType!Hash == int)); KeyType!Hash str = "a"; // str is declared as string ValueType!Hash num = 1; // num is declared as int
- template ValueType(V : V[K], K)
- Get the Value type of an Associative Array.Examples:
import std.traits; alias Hash = int[string]; static assert(is(KeyType!Hash == string)); static assert(is(ValueType!Hash == int)); KeyType!Hash str = "a"; // str is declared as string ValueType!Hash num = 1; // num is declared as int
- template Unsigned(T)
- Returns the corresponding unsigned type for T. T must be a numeric integral type, otherwise a compile-time error occurs.
- template Largest(T...) if (T.length >= 1)
- 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.Examples:
static assert(is(Largest!(uint, ubyte, ushort, real) == real)); static assert(is(Largest!(ulong, double) == ulong)); static assert(is(Largest!(double, ulong) == double)); static assert(is(Largest!(uint, byte, double, short) == double)); static if (is(ucent)) static assert(is(Largest!(uint, ubyte, ucent, ushort) == ucent));
- template Signed(T)
- Returns the corresponding signed type for T. T must be a numeric integral type, otherwise a compile-time error occurs.Examples:
alias S1 = Signed!uint; static assert(is(S1 == int)); alias S2 = Signed!(const(uint)); static assert(is(S2 == const(int))); alias S3 = Signed!(immutable(uint)); static assert(is(S3 == immutable(int))); static if (is(ucent)) { alias S4 = Signed!ucent; static assert(is(S4 == cent)); }
- template mostNegative(T) if (isNumeric!T || isSomeChar!T || isBoolean!T)
- Returns the most negative value of the numeric type T.Examples:
static assert(mostNegative!float == -float.max); static assert(mostNegative!double == -double.max); static assert(mostNegative!real == -real.max); static assert(mostNegative!bool == false);
Examples:foreach(T; TypeTuple!(bool, byte, short, int, long)) static assert(mostNegative!T == T.min); foreach(T; TypeTuple!(ubyte, ushort, uint, ulong, char, wchar, dchar)) static assert(mostNegative!T == 0);
- template mangledName(sth...) if (sth.length == 1)
- Returns the mangled name of symbol or type sth.mangledName is the same as builtin .mangleof property, except that the correct names of property functions are obtained.
module test; import std.traits : mangledName; class C { int value() @property; } pragma(msg, C.value.mangleof); // prints "i" pragma(msg, mangledName!(C.value)); // prints "_D4test1C5valueMFNdZi"
- template Select(bool condition, T...) if (T.length == 2)
- Aliases itself to T[0] if the boolean condition is true and to T[1] otherwise.Examples:
// can select types static assert(is(Select!(true, int, long) == int)); static assert(is(Select!(false, int, long) == long)); // can select symbols int a = 1; int b = 2; alias selA = Select!(true, a, b); alias selB = Select!(false, a, b); assert(selA == 1); assert(selB == 2);
- A select(bool cond : true, A, B)(A a, lazy B b);
B select(bool cond : false, A, B)(lazy A a, B b); - If cond is true, returns a without evaluating b. Otherwise, returns b without evaluating a.
- template hasUDA(alias symbol, alias attribute)
- Determine if a symbol has a given user-defined attribute.Examples:
enum E; struct S; struct Named { string name; } @("alpha") int a; static assert(hasUDA!(a, "alpha")); static assert(!hasUDA!(a, S)); static assert(!hasUDA!(a, E)); @(E) int b; static assert(!hasUDA!(b, "alpha")); static assert(!hasUDA!(b, S)); static assert(hasUDA!(b, E)); @E int c; static assert(!hasUDA!(c, "alpha")); static assert(!hasUDA!(c, S)); static assert(hasUDA!(c, E)); @(S, E) int d; static assert(!hasUDA!(d, "alpha")); static assert(hasUDA!(d, S)); static assert(hasUDA!(d, E)); @S int e; static assert(!hasUDA!(e, "alpha")); static assert(hasUDA!(e, S)); static assert(!hasUDA!(e, E)); @(S, E, "alpha") int f; static assert(hasUDA!(f, "alpha")); static assert(hasUDA!(f, S)); static assert(hasUDA!(f, E)); @(100) int g; static assert(hasUDA!(g, 100)); @Named("abc") int h; static assert(hasUDA!(h, Named));
- template getUDAs(alias symbol, alias attribute)
- Gets the user-defined attributes of the given type from the given symbol.Examples:
struct Attr { string name; int value; } @Attr("Answer", 42) int a; static assert(getUDAs!(a, Attr)[0].name == "Answer"); static assert(getUDAs!(a, Attr)[0].value == 42); @(Attr("Answer", 42), "string", 9999) int b; static assert(getUDAs!(b, Attr)[0].name == "Answer"); static assert(getUDAs!(b, Attr)[0].value == 42); @Attr("Answer", 42) @Attr("Pi", 3) int c; static assert(getUDAs!(c, Attr)[0].name == "Answer"); static assert(getUDAs!(c, Attr)[0].value == 42); static assert(getUDAs!(c, Attr)[1].name == "Pi"); static assert(getUDAs!(c, Attr)[1].value == 3);
- template getSymbolsByUDA(alias symbol, alias attribute)
- Gets all symbols within symbol that have the given user-defined attribute. This is not recursive; it will not search for symbols within symbols such as nested structs or unions.Examples:
enum Attr; static struct A { @Attr int a; int b; @Attr void doStuff() {} void doOtherStuff() {} static struct Inner { // Not found by getSymbolsByUDA @Attr int c; } } // Finds both variables and functions with the attribute, but // doesn't include the variables and functions without it. static assert(getSymbolsByUDA!(A, Attr).length == 2); // Can access attributes on the symbols returned by getSymbolsByUDA. static assert(hasUDA!(getSymbolsByUDA!(A, Attr)[0], Attr)); static assert(hasUDA!(getSymbolsByUDA!(A, Attr)[1], Attr)); static struct UDA { string name; } static struct B { @UDA("X") int x; @UDA("Y") int y; @(100) int z; } // Finds both UDA attributes. static assert(getSymbolsByUDA!(B, UDA).length == 2); // Finds one `100` attribute. static assert(getSymbolsByUDA!(B, 100).length == 1); // Can get the value of the UDA from the return value static assert(getUDAs!(getSymbolsByUDA!(B, UDA)[0], UDA)[0].name == "X"); @UDA("A") static struct C { @UDA("B") int d; } // Also checks the symbol itself static assert(getSymbolsByUDA!(C, UDA).length == 2); static assert(getSymbolsByUDA!(C, UDA)[0].stringof == "C"); static assert(getSymbolsByUDA!(C, UDA)[1].stringof == "d");