Templates which extract information about types and symbols at compile time.
Returns:T with theinout qualifier added.
Examples:staticassert(is(InoutOf!(int) ==inoutint));staticassert(is(InoutOf!(inoutint) ==inoutint));staticassert(is(InoutOf!(constint) ==inoutconstint));staticassert(is(InoutOf!(sharedint) ==inoutsharedint));
Returns:T with theconst qualifier added.
Examples:staticassert(is(ConstOf!(int) ==constint));staticassert(is(ConstOf!(constint) ==constint));staticassert(is(ConstOf!(inoutint) ==constinoutint));staticassert(is(ConstOf!(sharedint) ==constsharedint));
Returns:T with theshared qualifier added.
Examples:staticassert(is(SharedOf!(int) ==sharedint));staticassert(is(SharedOf!(sharedint) ==sharedint));staticassert(is(SharedOf!(inoutint) ==sharedinoutint));staticassert(is(SharedOf!(immutableint) ==sharedimmutableint));
Returns:T with theinout andshared qualifiers added.
Examples:staticassert(is(SharedInoutOf!(int) ==sharedinoutint));staticassert(is(SharedInoutOf!(int) ==inoutsharedint));staticassert(is(SharedInoutOf!(constint) ==sharedinoutconstint));staticassert(is(SharedInoutOf!(immutableint) ==sharedinoutimmutableint));
Returns:T with theconst andshared qualifiers added.
Examples:staticassert(is(SharedConstOf!(int) ==sharedconstint));staticassert(is(SharedConstOf!(int) ==constsharedint));staticassert(is(SharedConstOf!(inoutint) ==sharedinoutconstint));// immutable variables are implicitly shared and conststaticassert(is(SharedConstOf!(immutableint) ==immutableint));
template
SharedConstInoutOf(T)
Returns:T with theconst,shared, andinout qualifiers added.
Examples:staticassert(is(SharedConstInoutOf!(int) ==sharedconstinoutint));staticassert(is(SharedConstInoutOf!(int) ==constsharedinoutint));staticassert(is(SharedConstInoutOf!(inoutint) ==sharedinoutconstint));// immutable variables are implicitly shared and conststaticassert(is(SharedConstInoutOf!(immutableint) ==immutableint));
Returns:T with theimmutable qualifier added.
Examples:staticassert(is(ImmutableOf!(int) ==immutableint));staticassert(is(ImmutableOf!(constint) ==immutableint));staticassert(is(ImmutableOf!(inoutint) ==immutableint));staticassert(is(ImmutableOf!(sharedint) ==immutableint));
Gives a template that can be used to apply the same attributes that are on the given typeT. E.g. passinginout shared int will returnSharedInoutOf.
Parameters:| T | the type to check qualifiers from |
Returns:The qualifier template from the given typeT
Examples:staticassert(__traits(isSame,QualifierOf!(sharedconstinoutint), SharedConstInoutOf));staticassert(__traits(isSame,QualifierOf!(immutableint), ImmutableOf));staticassert(__traits(isSame,QualifierOf!(sharedint), SharedOf));staticassert(__traits(isSame,QualifierOf!(sharedinoutint), SharedInoutOf));import std.meta : Alias;staticassert(__traits(isSame,QualifierOf!(int), Alias));
template
packageName(alias T)
Get the full package name for the given symbol.
Examples:staticassert(packageName!packageName =="std");
Examples:staticassert(packageName!moduleName =="std");
template
moduleName(alias T)
Get the module name (including package) for the given symbol.
Examples:staticassert(moduleName!moduleName =="std.traits");
enum auto
fullyQualifiedName(T);
enum auto
fullyQualifiedName(alias T);
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 {}staticassert(fullyQualifiedName!(const MyStruct[]) =="const(myModule.MyStruct[])");Examples:staticassert(fullyQualifiedName!fullyQualifiedName =="std.traits.fullyQualifiedName");
template
ReturnType(alias func) if (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).
Note: To reduce template instantiations, consider instead usingtypeof(() { return func(args); } ()) if the argument types are known orstatic if (is(typeof(func) Ret == return)) if only that basic test is needed.
Examples:int foo();ReturnType!foo x;// x is declared as int
template
Parameters(alias func) if (isCallable!func)
Get, as a tuple, the types of the parameters to a function, a pointerto function, a delegate, a struct with anopCall, a pointer to astruct with anopCall, or a class with anopCall.
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(alias func) if (isCallable!func);
Alternate name for
Parameters, kept for legacy compatibility.
template
arity(alias func) if (isCallable!func && (variadicFunctionStyle!func == Variadic.no))
Returns the number of arguments of functionfunc.arity is undefined for variadic functions.
Examples:void foo(){}staticassert(arity!foo == 0);void bar(uint){}staticassert(arity!bar == 1);void variadicFoo(uint...){}staticassert(!__traits(compiles,arity!variadicFoo)); enum
ParameterStorageClass: uint;
template
ParameterStorageClassTuple(alias func) if (isCallable!func)
Get a tuple of the storage classes of a function's parameters.
Parameters:| func | function symbol or type of function, delegate, or pointer to function |
Returns:A tuple of ParameterStorageClass bits
Examples:alias STC =ParameterStorageClass;// shorten the enum namevoid func(refint ctx,outreal result,inreal param,void* ptr){}alias pstc =ParameterStorageClassTuple!func;staticassert(pstc.length == 4);// number of parametersstaticassert(pstc[0] == STC.ref_);staticassert(pstc[1] == STC.out_);version (none){// TODO: When the DMD PR (dlang/dmd#11474) gets merged,// remove the versioning and the second teststaticassert(pstc[2] == STC.in_);// This is the current behavior, before `in` is fixed to not be an aliasstaticassert(pstc[2] == STC.scope_);}staticassert(pstc[3] == STC.none); nonein_ref_out_lazy_scope_return_These flags can be bitwise OR-ed together to represent complex storage class.
enum ParameterStorageClass
extractParameterStorageClassFlags(Attribs...);
Parameters:| Attribs | The return value of__traits(getParameterStorageClasses) |
Examples:staticvoid func(refint ctx,outreal result);enum param1 =extractParameterStorageClassFlags!(__traits(getParameterStorageClasses, func, 0));staticassert(param1 == ParameterStorageClass.ref_);enum param2 =extractParameterStorageClassFlags!(__traits(getParameterStorageClasses, func, 1));staticassert(param2 == ParameterStorageClass.out_);enum param3 =extractParameterStorageClassFlags!(__traits(getParameterStorageClasses, func, 0),__traits(getParameterStorageClasses, func, 1));staticassert(param3 == (ParameterStorageClass.ref_ | ParameterStorageClass.out_));
template
ParameterIdentifierTuple(alias func) if (isCallable!func)
Get, as a tuple, the identifiers of the parameters to a function symbol.
Examples:int foo(int num, string name,int);staticassert([ParameterIdentifierTuple!foo] == ["num","name",""]);
template
ParameterDefaults(alias func) if (isCallable!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.
Examples:int foo(int num, string name ="hello",int[] = [1,2,3],lazyint x = 0);staticassert(is(ParameterDefaults!foo[0] ==void));staticassert(ParameterDefaults!foo[1] =="hello");staticassert(ParameterDefaults!foo[2] == [1,2,3]);staticassert(ParameterDefaults!foo[3] == 0);
alias
ParameterDefaultValueTuple = ParameterDefaults(alias func) if (isCallable!func);
enum
FunctionAttribute: uint;
template
functionAttributes(alias func) if (isCallable!func)
Returns the FunctionAttribute mask for functionfunc.
Examples:alias FA =FunctionAttribute;// shorten the enum namereal func(real x)purenothrow @safe{return x;}staticassert(functionAttributes!func & FA.pure_);staticassert(functionAttributes!func & FA.safe);staticassert(!(functionAttributes!func & FA.trusted));// not @trusted nonepure_nothrow_ref_propertytrustedsafenogcsystemconst_immutable_inout_shared_return_scope_liveThese flags can be bitwise OR-ed together to represent a complex attribute.
template
hasFunctionAttributes(args...) if (args.length > 0 && isCallable!(args[0]) && allSatisfy!(isSomeString, typeof(args[1..$])))
Checks whether a function has the given attributes attached.
Parameters:| args | Function to check, followed by a variadic number of function attributes as strings |
Returns:true, if the function has the list of attributes attached andfalse otherwise.
Examples:real func(real x)purenothrow @safe;staticassert(hasFunctionAttributes!(func,"@safe","pure"));staticassert(!hasFunctionAttributes!(func,"@trusted"));// for templates attributes are automatically inferredbool myFunc(T)(T b){return !b;}staticassert(hasFunctionAttributes!(myFunc!bool,"@safe","pure","@nogc","nothrow"));staticassert(!hasFunctionAttributes!(myFunc!bool,"shared")); template
isSafe(alias func) if (isCallable!func)
true iffunc is@safe or@trusted.
Examples:@safeint add(int a,int b) {return a+b;}@trustedint sub(int a,int b) {return a-b;}@systemint mul(int a,int b) {return a*b;}staticassert(isSafe!add);staticassert(isSafe!sub);staticassert(!isSafe!mul); enum auto
isUnsafe(alias func);
true iffunc is@system.
Examples:@safeint add(int a,int b) {return a+b;}@trustedint sub(int a,int b) {return a-b;}@systemint mul(int a,int b) {return a*b;}staticassert(!isUnsafe!add);staticassert(!isUnsafe!sub);staticassert(isUnsafe!mul); template
functionLinkage(alias func) if (isCallable!func)
Determine the linkage attribute of the function.
Parameters:| func | the function symbol, or the type of a function, delegate, or pointer to function |
Returns:one of the strings "D", "C", "C++", "Windows", "Objective-C", or "System".
Examples:extern(D)void Dfunc() {}extern(C)void Cfunc() {}staticassert(functionLinkage!Dfunc =="D");staticassert(functionLinkage!Cfunc =="C");string a =functionLinkage!Dfunc;writeln(a);// "D"auto fp = &Cfunc;string b =functionLinkage!fp;writeln(b);// "C" enum
Variadic: int;
template
variadicFunctionStyle(alias func) if (isCallable!func)
Determines what kind of variadic parameters function has.
Parameters:| func | function symbol or type of function, delegate, or pointer to function |
Examples:void func() {}staticassert(variadicFunctionStyle!func ==Variadic.no);extern(C)int printf(constchar*, ...);staticassert(variadicFunctionStyle!printf ==Variadic.c); Function is not variadic.
Function is a C-style variadic function, which usescore.stdc.stdarg
Function is a D-style variadic function, which uses__argptr and__arguments.
Function is a typesafe variadic function.
template
FunctionTypeOf(alias func) if (isCallable!func)
Get the function type from a callable objectfunc, or from a function pointer/delegate type.
Using builtintypeof on a property function yields the types of theproperty value, not of the property function itself. Still,FunctionTypeOf is able to obtain function types of properties.
NoteDo not confuse function types with function pointer types; function types areusually used for compile-time reflection purposes.
Examples:class C{int value() @property => 0;static string opCall() =>"hi";}staticassert(is(typeof(C.value) ==int ));staticassert(is(FunctionTypeOf!(C.value) ==function ));staticassert(is(FunctionTypeOf!C ==typeof(C.opCall) ));intfunction() fp;alias IntFn =int();staticassert(is(typeof(fp) == IntFn* ));staticassert(is(FunctionTypeOf!fp == IntFn )); 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 desiredFunctionAttributes 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_;returncast(SetFunctionAttributes!(T, functionLinkage!T, attrs)) t;}int f(){import core.thread : getpid;return getpid();}int g()pure @trusted{auto pureF = assumePure(&f);return pureF();}assert(g() > 0); template
isInnerClass(T) if (is(T == class))
Determines whetherT is a class nested inside another classand thatT.outer is the implicit reference to the outer class(i.e.outer has not been used as a field or method name)
Returns:true ifT is a class nested inside another, with the conditions described above;false otherwise
Examples:class C{int outer;}staticassert(!isInnerClass!C);class Outer1{class Inner1 { }class Inner2 {int outer; }}staticassert(isInnerClass!(Outer1.Inner1));staticassert(!isInnerClass!(Outer1.Inner2));staticclass Outer2{staticclass Inner {int outer; }}staticassert(!isInnerClass!(Outer2.Inner)); template
isNested(T) if (is(T == class) || is(T == struct) || is(T == union))
Determines whetherT has its own context pointer.T must be eitherclass,struct, orunion.
Examples:staticstruct S { }staticassert(!isNested!S);int i;struct NestedStruct {void f() { ++i; } }staticassert(isNested!NestedStruct); Determines whetherT or any of its representation typeshave a context pointer.
Examples:staticstruct S { }int i;struct NS {void f() { ++i; } }staticassert(!hasNested!(S[2]));staticassert(hasNested!(NS[2])); 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. IfT isn't a struct, class, interface or union returns a tuple with one elementT.
History:- ReturnedAliasSeq!(Interface) for interfaces prior to 2.097
Examples:import std.meta : AliasSeq;struct S {int x;float y; }staticassert(is(Fields!S == AliasSeq!(int,float))); alias
FieldTypeTuple = Fields(T);
Alternate name for
Fields, kept for legacy compatibility.
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. IfT isn't a struct, class, interface or union, an expression tuple with an empty string is returned.
History:- ReturnedAliasSeq!"" for interfaces prior to 2.097
Examples:import std.meta : AliasSeq;struct S {int x;float y; }staticassert(FieldNameTuple!S == AliasSeq!("x","y"));staticassert(FieldNameTuple!int == AliasSeq!""); template
RepresentationTypeTuple(T)
Get the primitive types of the fields of a struct or class, intopological 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*)); enum auto
hasAliasing(T...);
Returns
true if and only if
T's representation includes atleast one of the following:
- a raw pointerU* andUis not immutable;
- an arrayU[] andU is notimmutable;
- a reference to a class or interface typeC andC isnot 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; }staticassert(hasAliasing!S1);staticassert(!hasAliasing!S2);staticassert(!hasAliasing!S3);staticassert(!hasAliasing!S4); template
hasIndirections(T)
Returns
true if and only if
T's representation includes atleast one of the following:
- a raw pointerU*;
- anarrayU[];
- a reference to a class typeC;
- an associative array;
- a delegate;
- a
context pointer.
Examples:staticassert(hasIndirections!(int[string]));staticassert(hasIndirections!(voiddelegate()));staticassert(hasIndirections!(voiddelegate()immutable));staticassert(hasIndirections!(immutable(voiddelegate())));staticassert(hasIndirections!(immutable(voiddelegate()immutable)));staticassert(!hasIndirections!(voidfunction()));staticassert(hasIndirections!(void*[1]));staticassert(!hasIndirections!(byte[1]));
enum auto
hasUnsharedAliasing(T...);
Returns
true if and only if
T's representation includes atleast one of the following:
- a raw pointerU* andUis not immutable or shared;
- an arrayU[] andU is notimmutable or shared;
- a reference to a class typeC andC is not immutable or shared.
- an associative array that is notimmutable 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; }staticassert(hasUnsharedAliasing!S1);staticassert(!hasUnsharedAliasing!S2);staticassert(!hasUnsharedAliasing!S3);struct S4 {int a;shared Object b; }struct S5 {char[] a; }struct S6 {sharedchar[] b; }struct S7 {float[3] vals; }staticassert(!hasUnsharedAliasing!S4);staticassert(hasUnsharedAliasing!S5);staticassert(!hasUnsharedAliasing!S6);staticassert(!hasUnsharedAliasing!S7); template
hasElaborateCopyConstructor(S)
True ifS or any type embedded directly in the representation ofS defines an elaborate copy constructor. Elaborate copy constructors are introduced by definingthis(this) for astruct.
Classes and unions never have elaborate copy constructors.
template
hasElaborateAssign(S)
True ifS or any type directly embedded in the representation ofS defines an elaborate assignment. Elaborate assignments are introduced by definingopAssign(typeof(this)) oropAssign(ref typeof(this)) for astruct or when there is a compiler-generatedopAssign.
A type
S gets compiler-generated
opAssign if it has an elaborate destructor.
Classes and unions never have elaborate assignments.
NoteStructs with (possibly nested) postblit operator(s) will have a hidden yet elaborate compiler generated assignment operator (unless explicitly disabled).
Examples:staticassert(!hasElaborateAssign!int);staticstruct S {void opAssign(S) {} }staticassert(hasElaborateAssign!S);staticassert(!hasElaborateAssign!(const(S)));staticstruct S1 {void opAssign(ref S1) {} }staticstruct S2 {void opAssign(int) {} }staticstruct S3 { S s; }staticassert(hasElaborateAssign!S1);staticassert(!hasElaborateAssign!S2);staticassert(hasElaborateAssign!S3);staticassert(hasElaborateAssign!(S3[1]));staticassert(!hasElaborateAssign!(S3[0])); template
hasElaborateDestructor(S)
True ifS or any type directly embedded in the representation ofS 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().
template
hasElaborateMove(S)
True ifS or any type embedded directly in the representation ofS defines elaborate move semantics. Elaborate move semantics are introduced by definingopPostMove(ref typeof(this)) for astruct.
Classes and unions never have elaborate move semantics.
enum auto
hasMember(T, string name);
Yieldstrue if and only ifT is an aggregate that defines a symbol calledname.
Examples:staticassert(!hasMember!(int,"blah"));struct S1 {int blah; }struct S2 {int blah(){return 0; } }class C1 {int blah; }class C2 {int blah(){return 0; } }staticassert(hasMember!(S1,"blah"));staticassert(hasMember!(S2,"blah"));staticassert(hasMember!(C1,"blah"));staticassert(hasMember!(C2,"blah")); template
hasStaticMember(T, string member)
Whether the symbol represented by the string, member, exists and is a static member of T.
Parameters:| T | Type containing symbolmember. |
| member | Name of symbol to test that resides inT. |
Returns:true iffmember exists and is static.
Examples:staticstruct S{staticvoid sf() {}void f() {}staticint si;int i;}staticassert(hasStaticMember!(S,"sf"));staticassert(!hasStaticMember!(S,"f"));staticassert(hasStaticMember!(S,"si"));staticassert(!hasStaticMember!(S,"i"));staticassert(!hasStaticMember!(S,"hello")); template
EnumMembers(E) if (is(E == enum))
Retrieves the members of an enumerated typeenum 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. The name of the enum can be found by querying the compiler for the name of the identifier, i.e.
__traits(identifier,EnumMembers!MyEnum[i]). For enumerations with unique values,
std.conv.to can also be used.
NoteAn 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 thestd.meta.NoDuplicates template to avoid generating duplicate switch cases.
Note Returned values are strictly typed withE. 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:Create an array of enumerated values
enum Sqrts :real{ one = 1, two = 1.41421, three = 1.73205}auto sqrts = [EnumMembers!Sqrts];writeln(sqrts);// [Sqrts.one, Sqrts.two, Sqrts.three] Examples:A generic function
rank(v) in the following example uses thistemplate for finding a member
e in an enumerated type
E.
// Returns i if e is the i-th enumerator of E.static size_t rank(E)(E e)if (is(E ==enum)){staticforeach (i, member;EnumMembers!E) {if (e == member)return i; }assert(0,"Not an enum member");}enum Mode{ read = 1, write = 2, map = 4}writeln(rank(Mode.read));// 0writeln(rank(Mode.write));// 1writeln(rank(Mode.map));// 2 Examples:Use EnumMembers to generate a switch statement using static foreach.
import std.conv : to;class FooClass{ string calledMethod;void foo() @safe { calledMethod ="foo"; }void bar() @safe { calledMethod ="bar"; }void baz() @safe { calledMethod ="baz"; }}enum FooEnum { foo, bar, baz }auto var = FooEnum.bar;auto fooObj =new FooClass();s:finalswitch (var){staticforeach (member;EnumMembers!FooEnum) {case member:// Generate a case for each enum value.// Call fooObj.{name of enum value}().__traits(getMember, fooObj, to!string(member))();break s; }}// As we pass in FooEnum.bar, the bar() method gets called.writeln(fooObj.calledMethod);// "bar" Get aAliasSeq of the base class and base interfaces of this class or interface.BaseTypeTuple!Object returns the empty type tuple.
Examples:import std.meta : AliasSeq;interface I1 { }interface I2 { }interface I12 : I1, I2 { }staticassert(is(BaseTypeTuple!I12 == AliasSeq!(I1, I2)));interface I3 : I1 { }interface I123 : I1, I2, I3 { }staticassert(is(BaseTypeTuple!I123 == AliasSeq!(I1, I2, I3))); template
BaseClassesTuple(T) if (is(T == class))
Get aAliasSeq ofall base classes of this class, in decreasing order. Interfaces are not included. BaseClassesTuple!Object yields the empty type tuple.
Examples:import std.meta : AliasSeq;class C1 { }class C2 : C1 { }class C3 : C2 { }staticassert(!BaseClassesTuple!Object.length);staticassert(is(BaseClassesTuple!C1 == AliasSeq!(Object)));staticassert(is(BaseClassesTuple!C2 == AliasSeq!(C1, Object)));staticassert(is(BaseClassesTuple!C3 == AliasSeq!(C2, C1, Object))); template
InterfacesTuple(T)
Parameters:| T | Theclass orinterface to search. |
Returns:std.meta.AliasSeq of all interfaces directly or indirectly inherited by this class or interface. Interfaces do not repeat if multiply implemented.
InterfacesTuple!Object yields an empty
AliasSeq.
Examples:interface I1 {}interface I2 {}class A : I1, I2 {}class B : A, I1 {}class C : B {}alias TL =InterfacesTuple!C;staticassert(is(TL[0] == I1) &&is(TL[1] == I2)); template
TransitiveBaseTypeTuple(T)
Get aAliasSeq ofall base classes of T, in decreasing order, followed byT'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;writeln(TL.length);// 5assert(is (TL[0] == B2));assert(is (TL[1] == B1));assert(is (TL[2] == Object));assert(is (TL[3] == J1));assert(is (TL[4] == J2));writeln(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 namename declared in theclass or interfaceC. Covariant duplicates are shrunk into the mostderived one.
Examples:interface I { I foo(); }class B{real foo(real v) {return v; }}class C : B, I{override C foo() {returnthis; }// covariant overriding of I.foo()}alias foos =MemberFunctionsTuple!(C,"foo");staticassert(foos.length == 2);staticassert(__traits(isSame, foos[0], C.foo));staticassert(__traits(isSame, foos[1], B.foo)); template
TemplateOf(alias T : Base!Args, alias Base, Args...)
template
TemplateOf(alias T)
Returns an alias to the template thatT is an instance of.It will returnvoid if a symbol without a template is given.
Examples:struct Foo(T, U) {}staticassert(__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 aAliasSeq of the template arguments used to instantiateT.
Examples:import std.meta : AliasSeq;struct Foo(T, U) {}staticassert(is(TemplateArgsOf!(Foo!(int,real)) == AliasSeq!(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 pointerstaticassert(classInstanceAlignment!A == (void*).alignof);staticassert(classInstanceAlignment!B ==long.alignof); Get the type that all types can be implicitly converted to. Usefule.g. in figuring out an array type from a bunch of initializingvalues. Returnsvoid if passed an empty list, or if thetypes 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));
Examples:staticassert(is(CommonType!(3) ==int));staticassert(is(CommonType!(double, 4,float) ==double));staticassert(is(CommonType!(string,char[]) ==const(char)[]));staticassert(is(CommonType!(3, 3U) ==uint));staticassert(is(CommonType!(double,int) ==double));
template
AllImplicitConversionTargets(T)
Examples:import std.meta : AliasSeq;staticassert(is(AllImplicitConversionTargets!(ulong) == AliasSeq!(long,float,double,real)));staticassert(is(AllImplicitConversionTargets!(int) == AliasSeq!(dchar,uint,long,ulong,float,double,real)));staticassert(is(AllImplicitConversionTargets!(float) == AliasSeq!(double,real)));staticassert(is(AllImplicitConversionTargets!(double) == AliasSeq!(float,real)));staticassert(is(AllImplicitConversionTargets!(char) == AliasSeq!(byte,ubyte,short,ushort,wchar,int,dchar,uint,long,ulong,float,double,real)));staticassert(is(AllImplicitConversionTargets!(wchar) == AliasSeq!(short,ushort,dchar,int,uint,long,ulong,float,double,real)));staticassert(is(AllImplicitConversionTargets!(dchar) == AliasSeq!(int,uint,long,ulong,float,double,real)));staticassert(is(AllImplicitConversionTargets!(string) == AliasSeq!(const(char)[])));staticassert(is(AllImplicitConversionTargets!(int*) == AliasSeq!(void*)));interface A {}interface B {}class C : A, B {}staticassert(is(AllImplicitConversionTargets!(C) == AliasSeq!(Object, A, B)));staticassert(is(AllImplicitConversionTargets!(const C) == AliasSeq!(const Object,const A,const B)));staticassert(is(AllImplicitConversionTargets!(immutable C) == AliasSeq!(immutable Object,immutable A,immutable B)));interface I : A, B {}staticassert(is(AllImplicitConversionTargets!(I) == AliasSeq!(A, B)));staticassert(is(AllImplicitConversionTargets!(const I) == AliasSeq!(const A,const B)));staticassert(is(AllImplicitConversionTargets!(immutable I) == AliasSeq!(immutable A,immutable B))); template
ImplicitConversionTargets(T)
NoteThe possible targets are computed more conservatively than the language allows, eliminating all dangerous conversions. For example,ImplicitConversionTargets!double does not includefloat.
enum bool
isImplicitlyConvertible(From, To);
IsFrom implicitly convertible toTo?
Examples:staticassert(isImplicitlyConvertible!(immutable(char),char));staticassert(isImplicitlyConvertible!(const(char),char));staticassert(isImplicitlyConvertible!(char,wchar));staticassert(!isImplicitlyConvertible!(wchar,char));staticassert(!isImplicitlyConvertible!(const(ushort),ubyte));staticassert(!isImplicitlyConvertible!(const(uint),ubyte));staticassert(!isImplicitlyConvertible!(const(ulong),ubyte));staticassert(!isImplicitlyConvertible!(const(char)[], string));staticassert(isImplicitlyConvertible!(string,const(char)[]));
enum bool
isQualifierConvertible(From, To);
Examples:// Mutable and immmutable both convert to const...staticassert(isQualifierConvertible!(char,const(char)));staticassert(isQualifierConvertible!(immutable(char),const(char)));// ...but const does not convert back to mutable or immutablestaticassert(!isQualifierConvertible!(const(char),char));staticassert(!isQualifierConvertible!(const(char),immutable(char)));
enum auto
isAssignable(Lhs, Rhs = Lhs);
Returnstrue iff a value of typeRhs can be assigned to a variable oftypeLhs.
isAssignable returns whether both an lvalue and rvalue can be assigned.
If you omit
Rhs,
isAssignable will check identity assignable of
Lhs.
Examples:staticassert(isAssignable!(long,int));staticassert(!isAssignable!(int,long));staticassert(isAssignable!(const(char)[], string));staticassert(!isAssignable!(string,char[]));// int is assignable to intstaticassert(isAssignable!int);// immutable int is not assignable to immutable intstaticassert(!isAssignable!(immutableint));
enum auto
isRvalueAssignable(Lhs, Rhs = Lhs);
Returnstrue iff an rvalue of typeRhs can be assigned to a variable oftypeLhs.
Examples:struct S1{void opAssign(S1);}struct S2{void opAssign(ref S2);}staticassert(isRvalueAssignable!(long,int));staticassert(!isRvalueAssignable!(int,long));staticassert(isRvalueAssignable!S1);staticassert(!isRvalueAssignable!S2); enum auto
isLvalueAssignable(Lhs, Rhs = Lhs);
Returnstrue iff an lvalue of typeRhs can be assigned to a variable oftypeLhs.
Examples:struct S1{void opAssign(S1);}struct S2{void opAssign(ref S2);}staticassert(isLvalueAssignable!(long,int));staticassert(!isLvalueAssignable!(int,long));staticassert(isLvalueAssignable!S1);staticassert(isLvalueAssignable!S2); template
isCovariantWith(F, G) if (is(F == function) && is(G == function) || is(F == delegate) && is(G == delegate) || isFunctionPointer!F && isFunctionPointer!G)
Determines whether the function typeF is covariant withG, i.e.,functions of the typeF can override ones of the typeG.
Examples:interface I { I clone(); }interface J { J clone(); }class C : I{override C clone()// covariant overriding of I.clone() {returnnew C; }}// C.clone() can override I.clone(), indeed.staticassert(isCovariantWith!(typeof(C.clone),typeof(I.clone)));// C.clone() can't override J.clone(); the return type C is not implicitly// convertible to J.staticassert(!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.
NoteTrying to use returned value will result in a"Symbol Undefined" error at link time.
Examples:staticint f(int);staticassert(is(typeof(f(rvalueOf!int)) ==int));
Examples:staticbool f(refint);staticassert(is(typeof(f(lvalueOf!int)) ==bool));
Detect whetherT is a built-in boolean type or enum of boolean base type.
Examples:staticassert(isBoolean!bool);enum EB :bool { a =true }staticassert(isBoolean!EB);struct SubTypeOfBool{bool val;alias valthis;}staticassert(!isBoolean!(SubTypeOfBool)); Detect whetherT is a built-in integral type. Integral types arebyte,ubyte,short,ushort,int,uint,long,ulong,cent,ucent, and enums with an integral type as its base type.
Returns:true ifT is an integral type
Examples:staticassert(isIntegral!byte &&isIntegral!short &&isIntegral!int &&isIntegral!long &&isIntegral!(const(long)) &&isIntegral!(immutable(long)));staticassert( !isIntegral!bool && !isIntegral!char && !isIntegral!double);// types which act as integral values do not passstruct S{int val;alias valthis;}staticassert(!isIntegral!S); enum bool
isFloatingPoint(T);
Detect whetherT is a built-in floating point type.
Examples:staticassert(isFloatingPoint!float &&isFloatingPoint!double &&isFloatingPoint!real &&isFloatingPoint!(const(real)) &&isFloatingPoint!(immutable(real)));staticassert(!isFloatingPoint!int);// types which act as floating point values do not passstruct S{float val;alias valthis;}staticassert(!isFloatingPoint!S); Detect whetherT is a built-in numeric type (integral or floating point).
Examples:staticassert(isNumeric!byte &&isNumeric!short &&isNumeric!int &&isNumeric!long &&isNumeric!float &&isNumeric!double &&isNumeric!real &&isNumeric!(const(real)) &&isNumeric!(immutable(real)));staticassert( !isNumeric!void && !isNumeric!bool && !isNumeric!char && !isNumeric!wchar && !isNumeric!dchar);// types which act as numeric values do not passstruct S{int val;alias valthis;}staticassert(!isNumeric!S); enum bool
isScalarType(T);
Detect whetherT is a scalar type (a built-in numeric, character or boolean type).
Examples:staticassert(!isScalarType!void);staticassert(isScalarType!(immutable(byte)));staticassert(isScalarType!(immutable(ushort)));staticassert(isScalarType!(immutable(int)));staticassert(isScalarType!(ulong));staticassert(isScalarType!(shared(float)));staticassert(isScalarType!(shared(constbool)));staticassert(isScalarType!(const(char)));staticassert(isScalarType!(wchar));staticassert(isScalarType!(const(dchar)));staticassert(isScalarType!(const(double)));staticassert(isScalarType!(const(real)));
Detect whetherT is a basic type (scalar type or void).
Examples:staticassert(isBasicType!void);staticassert(isBasicType!(const(void)));staticassert(isBasicType!(shared(void)));staticassert(isBasicType!(immutable(void)));staticassert(isBasicType!(sharedconst(void)));staticassert(isBasicType!(sharedinout(void)));staticassert(isBasicType!(sharedinoutconst(void)));staticassert(isBasicType!(inout(void)));staticassert(isBasicType!(inoutconst(void)));staticassert(isBasicType!(immutable(int)));staticassert(isBasicType!(shared(float)));staticassert(isBasicType!(shared(constbool)));staticassert(isBasicType!(const(dchar)));
Detect whetherT is a built-in unsigned numeric type.
Examples:staticassert(isUnsigned!uint &&isUnsigned!ulong);staticassert( !isUnsigned!char && !isUnsigned!int && !isUnsigned!long && !isUnsigned!char && !isUnsigned!wchar && !isUnsigned!dchar);
Detect whetherT is a built-in signed numeric type.
Examples:staticassert(isSigned!int &&isSigned!long);staticassert( !isSigned!uint && !isSigned!ulong);
Detect whetherT is one of the built-in character types.
The built-in char types are any ofchar,wchar ordchar, with or without qualifiers.
Examples://Char typesstaticassert(isSomeChar!char);staticassert(isSomeChar!wchar);staticassert(isSomeChar!dchar);staticassert(isSomeChar!(typeof('c')));staticassert(isSomeChar!(immutablechar));staticassert(isSomeChar!(constdchar));//Non char typesstaticassert(!isSomeChar!int);staticassert(!isSomeChar!byte);staticassert(!isSomeChar!string);staticassert(!isSomeChar!wstring);staticassert(!isSomeChar!dstring);staticassert(!isSomeChar!(char[4])); enum bool
isSomeString(T);
Detect whetherT 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 consideredbuilt-in string types.
Examples://String typesstaticassert(isSomeString!string);staticassert(isSomeString!(wchar[]));staticassert(isSomeString!(dchar[]));staticassert(isSomeString!(typeof("aaa")));staticassert(isSomeString!(const(char)[]));//Non string typesstaticassert(!isSomeString!int);staticassert(!isSomeString!(int[]));staticassert(!isSomeString!(byte[]));staticassert(!isSomeString!(typeof(null)));staticassert(!isSomeString!(char[4]));enum ES : string { a ="aaa", b ="bbb" }staticassert(!isSomeString!ES);staticstruct Stringish{ string str;alias strthis;}staticassert(!isSomeString!Stringish); enum bool
isNarrowString(T);
Detect whether typeT is a narrow string.
All arrays that use char, wchar, and their qualified versions are narrow strings. (Those include string and wstring).
Examples:staticassert(isNarrowString!string);staticassert(isNarrowString!wstring);staticassert(isNarrowString!(char[]));staticassert(isNarrowString!(wchar[]));staticassert(!isNarrowString!dstring);staticassert(!isNarrowString!(dchar[]));staticassert(!isNarrowString!(typeof(null)));staticassert(!isNarrowString!(char[4]));enum ES : string { a ="aaa", b ="bbb" }staticassert(!isNarrowString!ES);staticstruct Stringish{ string str;alias strthis;}staticassert(!isNarrowString!Stringish); enum bool
isOrderingComparable(T);
enum bool
isEqualityComparable(T);
Detects whetherT is a comparable type. Basic types and structs and classes that implement opCmp are ordering comparable.
Examples:staticassert(isOrderingComparable!int);staticassert(isOrderingComparable!string);staticstruct Foo {}staticassert(!isOrderingComparable!Foo);staticstruct Bar{int a;auto opCmp(Bar b1)const {return a - b1.a; }}Bar b1 = Bar(5);Bar b2 = Bar(7);assert(isOrderingComparable!Bar && b2 > b1); enum auto
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.
Detect whetherT is a struct, static array, or enum that is implicitly convertible to a string.
Examples:staticstruct AliasedString{ string s;alias sthis;}enum StringEnum { a ="foo" }assert(!isConvertibleToString!string);assert(isConvertibleToString!AliasedString);assert(isConvertibleToString!StringEnum);assert(isConvertibleToString!(char[25]));assert(!isConvertibleToString!(char[])); enum auto
isAutodecodableString(T);
Detect whether typeT is a string that will be autodecoded.
Given a type
S that is one of:
- const(char)[]
- const(wchar)[]
Type
T can be one of:
- S
- implicitly convertible toT
- an enum with a base typeT
- an aggregate with a base typeT
with the proviso that
T cannot be a static array.
Returns:true if T represents a string that is subject to autodecoding
See Also:
isNarrowString Examples:staticstruct Stringish{ string s;alias sthis;}staticassert(isAutodecodableString!wstring);staticassert(isAutodecodableString!Stringish);staticassert(!isAutodecodableString!dstring);enum E :const(char)[3] { X ="abc" }enum F :const(char)[] { X ="abc" }enum G : F { X = F.init }staticassert(isAutodecodableString!(char[]));staticassert(!isAutodecodableString!(E));staticassert(isAutodecodableString!(F));staticassert(isAutodecodableString!(G));struct Stringish2{ Stringish s;alias sthis;}enum H : Stringish { X = Stringish() }enum I : Stringish2 { X = Stringish2() }staticassert(isAutodecodableString!(H));staticassert(isAutodecodableString!(I));staticassert(!isAutodecodableString!(noreturn[]));staticassert(!isAutodecodableString!(immutable(noreturn)[])); enum bool
isStaticArray(T);
Detect whether typeT is a static array.
Examples:staticassert(isStaticArray!(int[3]));staticassert(isStaticArray!(const(int)[5]));staticassert(isStaticArray!(const(int)[][5]));staticassert(!isStaticArray!(const(int)[]));staticassert(!isStaticArray!(immutable(int)[]));staticassert(!isStaticArray!(const(int)[4][]));staticassert(!isStaticArray!(int[]));staticassert(!isStaticArray!(int[char]));staticassert(!isStaticArray!(int[1][]));staticassert(!isStaticArray!(int[int]));staticassert(!isStaticArray!int);
template
isDynamicArray(T)
Detect whether typeT is a dynamic array.
Examples:staticassert(isDynamicArray!(int[]));staticassert(isDynamicArray!(string));staticassert(isDynamicArray!(long[3][]));staticassert(!isDynamicArray!(int[5]));staticassert(!isDynamicArray!(typeof(null)));
Detect whether type
T is an array (static or dynamic; for associative arrays see
isAssociativeArray).
Examples:staticassert(isArray!(int[]));staticassert(isArray!(int[5]));staticassert(isArray!(string));staticassert(!isArray!uint);staticassert(!isArray!(uint[uint]));staticassert(!isArray!(typeof(null)));
enum bool
isAssociativeArray(T);
Detect whetherT is an associative array type
Examples:struct S;staticassert(isAssociativeArray!(int[string]));staticassert(isAssociativeArray!(S[S]));staticassert(!isAssociativeArray!(string[]));staticassert(!isAssociativeArray!S);staticassert(!isAssociativeArray!(int[4]));
enum bool
isBuiltinType(T);
Detect whether typeT is a builtin type.
Examples:class C;union U;struct S;interface I;staticassert(isBuiltinType!void);staticassert(isBuiltinType!string);staticassert(isBuiltinType!(int[]));staticassert(isBuiltinType!(C[string]));staticassert(isBuiltinType!(typeof(null)));staticassert(!isBuiltinType!C);staticassert(!isBuiltinType!U);staticassert(!isBuiltinType!S);staticassert(!isBuiltinType!I);staticassert(!isBuiltinType!(voiddelegate(int)));
enum bool
isSIMDVector(T);
Detect whether typeT is a SIMD vector type.
Examples:staticif (is(__vector(float[4]))){alias SimdVec =__vector(float[4]);staticassert(isSIMDVector!(__vector(float[4])));staticassert(isSIMDVector!SimdVec);}staticassert(!isSIMDVector!uint);staticassert(!isSIMDVector!(float[4])); Detect whether typeT is a pointer.
Examples:void fun();staticassert(isPointer!(int*));staticassert(isPointer!(intfunction()));staticassert(!isPointer!int);staticassert(!isPointer!string);staticassert(!isPointer!(typeof(null)));staticassert(!isPointer!(typeof(fun)));staticassert(!isPointer!(intdelegate()));
template
PointerTarget(T : T*)
Returns the target type of a pointer.
Examples:staticassert(is(PointerTarget!(int*) ==int));staticassert(is(PointerTarget!(void*) ==void));
template
isAggregateType(T)
Detect whether typeT is an aggregate type.
Examples:class C {}union U {}struct S {}interface I {}staticassert(isAggregateType!C);staticassert(isAggregateType!U);staticassert(isAggregateType!S);staticassert(isAggregateType!I);staticassert(!isAggregateType!void);staticassert(!isAggregateType!string);staticassert(!isAggregateType!(int[]));staticassert(!isAggregateType!(C[string]));staticassert(!isAggregateType!(voiddelegate(int)));enum ES : S { a = S.init }enum EC : C { a = C.init }enum EI : I { a = I.init }enum EU : U { a = U.init }staticassert(isAggregateType!ES);staticassert(isAggregateType!EC);staticassert(isAggregateType!EI);staticassert(isAggregateType!EU); Returnstrue if T can be iterated over using aforeach loop with a single loop variable of automatically inferred type, regardless of how theforeach loop is implemented. This includes ranges, structs/classes that defineopApply with a single loop variable, and builtin dynamic, static and associative arrays.
Examples:struct OpApply{int opApply(scopeintdelegate(refuint) dg) {assert(0); }}struct Range{ @propertyuint front() {assert(0); }void popFront() {assert(0); }enumbool empty =false;}staticassert(isIterable!(uint[]));staticassert(isIterable!OpApply);staticassert(isIterable!(uint[string]));staticassert(isIterable!Range);staticassert(!isIterable!uint); 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:staticassert(isMutable!int);staticassert(isMutable!string);staticassert(isMutable!(sharedint));staticassert(isMutable!(sharedconst(int)[]));staticassert(!isMutable!(constint));staticassert(!isMutable!(inoutint));staticassert(!isMutable!(shared(constint)));staticassert(!isMutable!(shared(inoutint)));staticassert(!isMutable!(immutable string));
enum bool
isInstanceOf(alias S, T);
enum auto
isInstanceOf(alias S, alias T);
Returns true if T is an instance of the template S.
Examples:staticstruct Foo(T...) { }staticstruct Bar(T...) { }staticstruct Doo(T) { }staticstruct ABC(int x) { }staticvoid fun(T)() { }template templ(T) { }staticassert(isInstanceOf!(Foo, Foo!int));staticassert(!isInstanceOf!(Foo, Bar!int));staticassert(!isInstanceOf!(Foo,int));staticassert(isInstanceOf!(Doo, Doo!int));staticassert(isInstanceOf!(ABC, ABC!1));staticassert(!isInstanceOf!(Foo, Foo));staticassert(isInstanceOf!(fun, fun!int));staticassert(isInstanceOf!(templ, templ!int)); Examples:To use
isInstanceOf to check the identity of a template while inside of said template, use
TemplateOf.
staticstruct A(T =void){// doesn't work as expected, only accepts A when T = voidvoid func(B)(B b)if (isInstanceOf!(A, B)) {}// correct behaviorvoid method(B)(B b)if (isInstanceOf!(TemplateOf!(A), B)) {}}A!(void) a1;A!(void) a2;A!(int) a3;staticassert(!__traits(compiles, a1.func(a3)));staticassert(__traits(compiles, a1.method(a2)));staticassert(__traits(compiles, a1.method(a3))); template
isExpressions(T...)
Check whether the tuple T is an expression tuple. An expression tuple only contains expressions.
Examples:staticassert(isExpressions!(1, 2.0,"a"));staticassert(!isExpressions!(int,double, string));staticassert(!isExpressions!(int, 2.0,"a"));
alias
isExpressionTuple = isExpressions(T...);
enum auto
isTypeTuple(T...);
Check whether the tupleT is a type tuple. A type tuple only contains types.
Examples:staticassert(isTypeTuple!(int,float, string));staticassert(!isTypeTuple!(1, 2.0,"a"));staticassert(!isTypeTuple!(1,double, string));
enum bool
isFunctionPointer(alias T);
Detect whether symbol or typeT is a function pointer.
Examples:staticvoid foo() {}void bar() {}auto fpfoo = &foo;staticassert(isFunctionPointer!fpfoo);staticassert(isFunctionPointer!(voidfunction()));auto dgbar = &bar;staticassert(!isFunctionPointer!dgbar);staticassert(!isFunctionPointer!(voiddelegate()));staticassert(!isFunctionPointer!foo);staticassert(!isFunctionPointer!bar);staticassert(isFunctionPointer!((int a) {})); enum bool
isDelegate(alias T);
Detect whether symbol or typeT is a delegate.
Examples:staticvoid sfunc() { }int x;void func() { x++; }intdelegate() dg;assert(isDelegate!dg);assert(isDelegate!(intdelegate()));assert(isDelegate!(typeof(&func)));intfunction() fp;assert(!isDelegate!fp);assert(!isDelegate!(intfunction()));assert(!isDelegate!(typeof(&sfunc))); enum bool
isSomeFunction(alias T);
Detect whether symbol or typeT is a function, a function pointer or a delegate.
Examples:staticreal func(refint) {return 0; }staticvoid prop() @property { }class C{real method(refint) {return 0; }real prop() @property {return 0; }}auto c =new C;auto fp = &func;auto dg = &c.method;staticassert(isSomeFunction!func);staticassert(isSomeFunction!prop);staticassert(isSomeFunction!(C.method));staticassert(isSomeFunction!(C.prop));staticassert(isSomeFunction!(c.prop));staticassert(isSomeFunction!fp);staticassert(isSomeFunction!dg);real val;staticassert(!isSomeFunction!int);staticassert(!isSomeFunction!val); template
isCallable(alias callable)
Detect whetherT is a callable object, which can be called with thefunction call operator(...).
Note: Implicit Function Template Instantiation isnot attempted - see below.
Examples:Functions, function pointers, delegates, lambdas.
void f() { }int g(int x) {return x; }staticassert(isCallable!f);staticassert(isCallable!g);auto fp = &f;staticassert(isCallable!fp);staticassert(isCallable!((int x) {}));int x;staticassert(!isCallable!x); Examples:Aggregate types with (static) opCall.
class C {int opCall(int) {return 0; } }auto c =new C;struct S {staticint opCall(int) {return 0; } }interface I {real value() @property; }staticassert(isCallable!c);staticassert(isCallable!(c.opCall));staticassert(isCallable!S);staticassert(isCallable!(I.value));staticassert(isCallable!((int a) {return a; }));staticassert(!isCallable!I); Examples:Template functions are only detected if they are instantiable with
!().
void f()() { }T g(T =int)(T x) {return x; }struct S1 {staticvoid opCall()() { } }struct S2 {static T opCall(T =int)(T x) {return x; } }staticassert(isCallable!f);staticassert(isCallable!g);staticassert(isCallable!S1);staticassert(isCallable!S2);staticassert(!isCallable!((x) {})); Examples:Overloaded functions and function templates instantiable with
!().
staticstruct Wrapper{void f() { }int f(int x) {return x; }void g()() { } T g(T =int)(T x) {return x; }}staticassert(isCallable!(Wrapper.f));staticassert(isCallable!(Wrapper.g)); enum auto
isAbstractFunction(alias S);
Detect whetherS is an abstract function.
Examples:struct S {void foo() { } }class C {void foo() { } }class AC {abstractvoid foo(); }staticassert(!isAbstractFunction!(int));staticassert(!isAbstractFunction!(S.foo));staticassert(!isAbstractFunction!(C.foo));staticassert(isAbstractFunction!(AC.foo)); enum auto
isFinalFunction(alias S);
Detect whetherS is a final function.
Examples:struct S {void bar() { } }finalclass FC {void foo(); }class C{void bar() { }finalvoid foo();}staticassert(!isFinalFunction!(int));staticassert(!isFinalFunction!(S.bar));staticassert(isFinalFunction!(FC.foo));staticassert(!isFinalFunction!(C.bar));staticassert(isFinalFunction!(C.foo)); enum auto
isNestedFunction(alias f);
Determines iff is a function that requires a context pointer.
Parameters:| f | The type to checkReturns Abool |
Examples:staticvoid f() {}staticvoid fun(){int i;int f() {return i; }staticassert(isNestedFunction!(f));}staticassert(!isNestedFunction!f); enum auto
isAbstractClass(alias S);
Detect whetherS is an abstract class.
Examples:struct S { }class C { }abstractclass AC { }staticassert(!isAbstractClass!S);staticassert(!isAbstractClass!C);staticassert(isAbstractClass!AC);C c;staticassert(!isAbstractClass!c);AC ac;staticassert(isAbstractClass!ac); enum auto
isFinalClass(alias S);
Detect whetherS is a final class.
Examples:class C { }abstractclass AC { }finalclass FC1 : C { }finalclass FC2 { }staticassert(!isFinalClass!C);staticassert(!isFinalClass!AC);staticassert(isFinalClass!FC1);staticassert(isFinalClass!FC2);C c;staticassert(!isFinalClass!c);FC1 fc1;staticassert(isFinalClass!fc1); Removesconst,inout andimmutable qualifiers, if any, from typeT.
Removesshared qualifier, if any, from typeT.
Note that whileimmutable is implicitlyshared, it is unaffected by Unshared. Only explictshared is removed.
Examples:staticassert(is(Unshared!int ==int));staticassert(is(Unshared!(constint) ==constint));staticassert(is(Unshared!(immutableint) ==immutableint));staticassert(is(Unshared!(sharedint) ==int));staticassert(is(Unshared!(shared(constint)) ==constint));staticassert(is(Unshared!(shared(int[])) ==shared(int)[]));
Removes all qualifiers, if any, from typeT.
template
CopyTypeQualifiers(FromType, ToType)
Copies type qualifiers fromFromType toToType.
Supported type qualifiers:
- const
- inout
- immutable
- shared
Examples:staticassert(is(CopyTypeQualifiers!(inoutconstreal,int) ==inoutconstint));
template
CopyConstness(FromType, ToType)
Returns the type ofToType with the "constness" ofFromType. A type'sconstnessrefers to whether it isconst,immutable, orinout. IfFromType has no constness, thereturned type will be the same asToType.
Examples:const(int) i;CopyConstness!(typeof(i),float) f;assert(is(typeof(f) ==constfloat));CopyConstness!(char,uint) u;assert(is(typeof(u) ==uint));//The 'shared' qualifier will not be copiedassert(!is(CopyConstness!(sharedbool,int) ==sharedint));//But the constness will beassert(is(CopyConstness!(sharedconstreal,double) ==constdouble));//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 intsalias CstT =CopyConstness!(const(int[]),int);assert(is(CstT ==const(int)));
Returns the inferred type of the loop variable when a variable of type Tis iterated over using aforeach loop with a single loop variable andautomatically inferred return type. Note that this may not be the same asstd.range.ElementType!Range in the case of narrow strings, or if Thas both opApply and a range interface.
Examples:staticassert(is(ForeachType!(uint[]) ==uint));staticassert(is(ForeachType!string ==immutable(char)));staticassert(is(ForeachType!(string[string]) == string));staticassert(is(ForeachType!(inout(int)[]) ==inout(int)));
Strips off allenums from typeT.
Examples:enum E :real { a = 0 }// NOTE: explicit initialization to 0 required during Enum init deprecation cycleenum F : E { a = E.a }alias G =const(F);staticassert(is(OriginalType!E ==real));staticassert(is(OriginalType!F ==real));staticassert(is(OriginalType!G ==constreal)); template
KeyType(V : V[K], K)
Get the Key type of an Associative Array.
Examples:alias Hash =int[string];staticassert(is(KeyType!Hash == string));staticassert(is(ValueType!Hash ==int));KeyType!Hash str ="a";// str is declared as stringValueType!Hash num = 1;// num is declared as int
template
ValueType(V : V[K], K)
Get the Value type of an Associative Array.
Examples:alias Hash =int[string];staticassert(is(KeyType!Hash == string));staticassert(is(ValueType!Hash ==int));KeyType!Hash str ="a";// str is declared as stringValueType!Hash num = 1;// num is declared as int
Parameters:| T | A built in integral or vector type. |
Returns:The corresponding unsigned numeric type for
T with the same type qualifiers.
If
T is not a integral or vector, a compile-time error is given.
Examples:staticassert(is(Unsigned!(int) ==uint));staticassert(is(Unsigned!(long) ==ulong));staticassert(is(Unsigned!(constshort) ==constushort));staticassert(is(Unsigned!(immutablebyte) ==immutableubyte));staticassert(is(Unsigned!(inoutint) ==inoutuint));
Examples:Unsigned types are forwarded
staticassert(is(Unsigned!(uint) ==uint));staticassert(is(Unsigned!(constuint) ==constuint));staticassert(is(Unsigned!(ubyte) ==ubyte));staticassert(is(Unsigned!(immutableuint) ==immutableuint));
template
Largest(T...) if (T.length >= 1)
Returns the largest type, i.e. T such that T.sizeof is the largest. If morethan one type is of the same size, the leftmost argument of these in will bereturned.
Examples:staticassert(is(Largest!(uint,ubyte,ushort,real) ==real));staticassert(is(Largest!(ulong,double) ==ulong));staticassert(is(Largest!(double,ulong) ==double));staticassert(is(Largest!(uint,byte,double,short) ==double));staticif (is(ucent))staticassert(is(Largest!(uint,ubyte,ucent,ushort) ==ucent));
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;staticassert(is(S1 ==int));alias S2 =Signed!(const(uint));staticassert(is(S2 ==const(int)));alias S3 =Signed!(immutable(uint));staticassert(is(S3 ==immutable(int)));staticif (is(ucent)){alias S4 =Signed!ucent;staticassert(is(S4 ==cent));} template
mostNegative(T) if (isNumeric!T || isSomeChar!T || isBoolean!T)
Returns the most negative value of the numeric type T.
Examples:staticassert(mostNegative!float == -float.max);staticassert(mostNegative!double == -double.max);staticassert(mostNegative!real == -real.max);staticassert(mostNegative!bool ==false);
Examples:import std.meta : AliasSeq;staticforeach (T; AliasSeq!(bool,byte,short,int,long))staticassert(mostNegative!T == T.min);staticforeach (T; AliasSeq!(ubyte,ushort,uint,ulong,char,wchar,dchar))staticassert(mostNegative!T == 0);
template
Promoted(T) if (isScalarType!T)
Get the type that a scalar type
T will
promoteto in multi-term arithmetic expressions.
Examples:ubyte a = 3, b = 5;staticassert(is(typeof(a * b) ==Promoted!ubyte));staticassert(is(Promoted!ubyte ==int));staticassert(is(Promoted!(shared(bool)) ==shared(int)));staticassert(is(Promoted!(const(int)) ==const(int)));staticassert(is(Promoted!double ==double));
enum auto
mangledName(alias sth);
Returns the mangled name of symbol or typesth.
mangledName is the same as builtin.mangleof property, butmight be more convenient in generic code, e.g. as a template argumentwhen invoking staticMap.
Examples:import std.meta : AliasSeq;alias TL = staticMap!(mangledName,int,constint,immutableint);staticassert(TL == AliasSeq!("i","xi","yi")); template
Select(bool condition, T...) if (T.length == 2)
Aliases itself toT[0] if the booleancondition istrueand toT[1] otherwise.
Examples:// can select typesstaticassert(is(Select!(true,int,long) ==int));staticassert(is(Select!(false,int,long) ==long));staticstruct Foo {}staticassert(is(Select!(false,const(int),const(Foo)) ==const(Foo)));// can select symbolsint a = 1;int b = 2;alias selA =Select!(true, a, b);alias selB =Select!(false, a, b);writeln(selA);// 1writeln(selB);// 2// can select (compile-time) expressionsenum val =Select!(false, -4, 9 - 6);staticassert(val == 3); A
select(bool cond : true, A, B)(A
a, lazy B
b);
B
select(bool cond : false, A, B)(lazy A
a, B
b);
Select one of two functions to run via template parameter.
Parameters:| cond | Abool which determines which function is run |
Aa | The first function |
Bb | The second function |
Returns:a without evaluatingb ifcond istrue. Otherwise, returnsb without evaluatinga.
Examples:real run() {return 0; }int fail() {assert(0); }autoa =select!true(run(), fail());autob =select!false(fail(), run());staticassert(is(typeof(a) ==real));staticassert(is(typeof(b) ==real)); enum auto
hasUDA(alias symbol, alias attribute);
Examples:enum E;struct S {}@("alpha")int a;staticassert(hasUDA!(a,"alpha"));staticassert(!hasUDA!(a, S));staticassert(!hasUDA!(a, E));@(E)int b;staticassert(!hasUDA!(b,"alpha"));staticassert(!hasUDA!(b, S));staticassert(hasUDA!(b, E));@Eint c;staticassert(!hasUDA!(c,"alpha"));staticassert(!hasUDA!(c, S));staticassert(hasUDA!(c, E));@(S, E)int d;staticassert(!hasUDA!(d,"alpha"));staticassert(hasUDA!(d, S));staticassert(hasUDA!(d, E));@Sint e;staticassert(!hasUDA!(e,"alpha"));staticassert(hasUDA!(e, S));staticassert(!hasUDA!(e, S()));staticassert(!hasUDA!(e, E));@S()int f;staticassert(!hasUDA!(f,"alpha"));staticassert(hasUDA!(f, S));staticassert(hasUDA!(f, S()));staticassert(!hasUDA!(f, E));@(S, E,"alpha")int g;staticassert(hasUDA!(g,"alpha"));staticassert(hasUDA!(g, S));staticassert(hasUDA!(g, E));@(100)int h;staticassert(hasUDA!(h, 100));struct Named { string name; }@Named("abc")int i;staticassert(hasUDA!(i, Named));staticassert(hasUDA!(i, Named("abc")));staticassert(!hasUDA!(i, Named("def")));struct AttrT(T){ string name; T value;}@AttrT!int("answer", 42)int j;staticassert(hasUDA!(j, AttrT));staticassert(hasUDA!(j, AttrT!int));staticassert(!hasUDA!(j, AttrT!string));@AttrT!string("hello","world")int k;staticassert(hasUDA!(k, AttrT));staticassert(!hasUDA!(k, AttrT!int));staticassert(hasUDA!(k, AttrT!string));struct FuncAttr(alias f) {alias func = f; }staticint fourtyTwo() {return 42; }static size_t getLen(string s) {return s.length; }@FuncAttr!getLenint l;staticassert(hasUDA!(l, FuncAttr));staticassert(!hasUDA!(l, FuncAttr!fourtyTwo));staticassert(hasUDA!(l, FuncAttr!getLen));staticassert(!hasUDA!(l, FuncAttr!fourtyTwo()));staticassert(!hasUDA!(l, FuncAttr!getLen()));@FuncAttr!getLen()int m;staticassert(hasUDA!(m, FuncAttr));staticassert(!hasUDA!(m, FuncAttr!fourtyTwo));staticassert(hasUDA!(m, FuncAttr!getLen));staticassert(!hasUDA!(m, FuncAttr!fourtyTwo()));staticassert(hasUDA!(m, FuncAttr!getLen())); template
getUDAs(alias symbol, alias attribute)
If the UDA is a type, then any UDAs of the same type on the symbol will match. If the UDA is a template for a type, then any UDA which is an instantiation of that template will match. And if the UDA is a value, then any UDAs on the symbol which are equal to that value will match.
Examples:struct Attr{ string name;int value;}@Attr("Answer", 42)int a;staticassert(getUDAs!(a, Attr).length == 1);staticassert(getUDAs!(a, Attr)[0].name =="Answer");staticassert(getUDAs!(a, Attr)[0].value == 42);@(Attr("Answer", 42),"string", 9999)int b;staticassert(getUDAs!(b, Attr).length == 1);staticassert(getUDAs!(b, Attr)[0].name =="Answer");staticassert(getUDAs!(b, Attr)[0].value == 42);@Attr("Answer", 42) @Attr("Pi", 3)int c;staticassert(getUDAs!(c, Attr).length == 2);staticassert(getUDAs!(c, Attr)[0].name =="Answer");staticassert(getUDAs!(c, Attr)[0].value == 42);staticassert(getUDAs!(c, Attr)[1].name =="Pi");staticassert(getUDAs!(c, Attr)[1].value == 3);staticassert(getUDAs!(c, Attr("Answer", 42)).length == 1);staticassert(getUDAs!(c, Attr("Answer", 42))[0].name =="Answer");staticassert(getUDAs!(c, Attr("Answer", 42))[0].value == 42);staticassert(getUDAs!(c, Attr("Answer", 99)).length == 0);struct AttrT(T){ string name; T value;}@AttrT!uint("Answer", 42) @AttrT!int("Pi", 3) @AttrTint d;staticassert(getUDAs!(d, AttrT).length == 2);staticassert(getUDAs!(d, AttrT)[0].name =="Answer");staticassert(getUDAs!(d, AttrT)[0].value == 42);staticassert(getUDAs!(d, AttrT)[1].name =="Pi");staticassert(getUDAs!(d, AttrT)[1].value == 3);staticassert(getUDAs!(d, AttrT!uint).length == 1);staticassert(getUDAs!(d, AttrT!uint)[0].name =="Answer");staticassert(getUDAs!(d, AttrT!uint)[0].value == 42);staticassert(getUDAs!(d, AttrT!int).length == 1);staticassert(getUDAs!(d, AttrT!int)[0].name =="Pi");staticassert(getUDAs!(d, AttrT!int)[0].value == 3);struct SimpleAttr {}@SimpleAttrint e;staticassert(getUDAs!(e, SimpleAttr).length == 1);staticassert(is(getUDAs!(e, SimpleAttr)[0] == SimpleAttr));@SimpleAttr()int f;staticassert(getUDAs!(f, SimpleAttr).length == 1);staticassert(is(typeof(getUDAs!(f, SimpleAttr)[0]) == SimpleAttr));struct FuncAttr(alias f) {alias func = f; }staticint add42(int v) {return v + 42; }static string concat(string l, string r) {return l ~ r; }@FuncAttr!add42int g;staticassert(getUDAs!(g, FuncAttr).length == 1);staticassert(getUDAs!(g, FuncAttr)[0].func(5) == 47);staticassert(getUDAs!(g, FuncAttr!add42).length == 1);staticassert(getUDAs!(g, FuncAttr!add42)[0].func(5) == 47);staticassert(getUDAs!(g, FuncAttr!add42()).length == 0);staticassert(getUDAs!(g, FuncAttr!concat).length == 0);staticassert(getUDAs!(g, FuncAttr!concat()).length == 0);@FuncAttr!add42()int h;staticassert(getUDAs!(h, FuncAttr).length == 1);staticassert(getUDAs!(h, FuncAttr)[0].func(5) == 47);staticassert(getUDAs!(h, FuncAttr!add42).length == 1);staticassert(getUDAs!(h, FuncAttr!add42)[0].func(5) == 47);staticassert(getUDAs!(h, FuncAttr!add42()).length == 1);staticassert(getUDAs!(h, FuncAttr!add42())[0].func(5) == 47);staticassert(getUDAs!(h, FuncAttr!concat).length == 0);staticassert(getUDAs!(h, FuncAttr!concat()).length == 0);@("alpha") @(42)int i;staticassert(getUDAs!(i,"alpha").length == 1);staticassert(getUDAs!(i,"alpha")[0] =="alpha");staticassert(getUDAs!(i, 42).length == 1);staticassert(getUDAs!(i, 42)[0] == 42);staticassert(getUDAs!(i, 'c').length == 0); template
getSymbolsByUDA(alias symbol, alias attribute)
Parameters:| symbol | The aggregate type or module to search |
| attribute | The user-defined attribute to search for |
Returns:All symbols withinsymbol that have the given UDAattribute.
NoteThis is not recursive; it will not search for symbols within symbols such as nested structs or unions.
Examples:enum Attr;struct A{ @Attrint a;int b;}staticassert(getSymbolsByUDA!(A, Attr).length == 1);staticassert(hasUDA!(getSymbolsByUDA!(A, Attr)[0], Attr)); Examples:enum Attr;staticstruct A{ @Attrint a;int b; @Attrvoid doStuff() {}void doOtherStuff() {}staticstruct Inner {// Not found by getSymbolsByUDA @Attrint c; }}// Finds both variables and functions with the attribute, but// doesn't include the variables and functions without it.staticassert(getSymbolsByUDA!(A, Attr).length == 2);// Can access attributes on the symbols returned by getSymbolsByUDA.staticassert(hasUDA!(getSymbolsByUDA!(A, Attr)[0], Attr));staticassert(hasUDA!(getSymbolsByUDA!(A, Attr)[1], Attr)); Examples:Finds multiple attributes
staticstruct UDA { string name; }staticstruct B{ @UDA("X")int x; @UDA("Y")int y; @(100)int z;}// Finds both UDA attributes.staticassert(getSymbolsByUDA!(B, UDA).length == 2);// Finds one `100` attribute.staticassert(getSymbolsByUDA!(B, 100).length == 1);// Can get the value of the UDA from the return valuestaticassert(getUDAs!(getSymbolsByUDA!(B, UDA)[0], UDA)[0].name =="X"); Examples:Checks for UDAs on the aggregate symbol itself
staticstruct UDA { string name; }@UDA("A")staticstruct C{ @UDA("B")int d;}staticassert(getSymbolsByUDA!(C, UDA).length == 2);staticassert(getSymbolsByUDA!(C, UDA)[0].stringof =="C");staticassert(getSymbolsByUDA!(C, UDA)[1].stringof =="d"); Examples:Finds nothing if there is no member with specific UDA
staticstruct UDA { string name; }staticstruct D{int x;}staticassert(getSymbolsByUDA!(D, UDA).length == 0); enum bool
allSameType(Ts...);
Returns:true iff all typesTs are the same.
Examples:staticassert(allSameType!());staticassert(allSameType!(int));staticassert(allSameType!(int,int));staticassert(allSameType!(int,int,int));staticassert(allSameType!(float,float,float));staticassert(!allSameType!(int,double));staticassert(!allSameType!(int,float,double));staticassert(!allSameType!(int,float,double,real));staticassert(!allSameType!(short,int,float,double,real));
enum auto
ifTestable(T, alias pred = (a) => a);
Returns:true iff the typeT can be tested in an if-expression, that is ifif (pred(T.init)) {} is compilable.
Examples:class C;struct S1;struct S2{ T opCast(T)()const;}staticassert(ifTestable!bool);staticassert(ifTestable!int);staticassert(ifTestable!(S1*));staticassert(ifTestable!(typeof(null)));staticassert(ifTestable!(int[]));staticassert(ifTestable!(int[string]));staticassert(ifTestable!S2);staticassert(ifTestable!C);staticassert(!ifTestable!S1); enum auto
isType(alias X);
Detect whetherX is a type. Analogous tois(X). This is useful when used in conjunction with other templates, e.g.allSatisfy!(isType, X).
Returns:true ifX is a type,false otherwise
Examples:struct S {template Test() {}}class C {}interface I {}union U {}staticassert(isType!int);staticassert(isType!string);staticassert(isType!(int[int]));staticassert(isType!S);staticassert(isType!C);staticassert(isType!I);staticassert(isType!U);int n;void func(){}staticassert(!isType!n);staticassert(!isType!func);staticassert(!isType!(S.Test));staticassert(!isType!(S.Test!())); template
isFunction(alias X)
Detect whether symbol or typeX is a function. This is different that finding if a symbol is callable or satisfyingis(X == function), it finds specifically if the symbol represents a normal function declaration, i.e. not a delegate or a function pointer.
Returns:true ifX is a function,false otherwise
Examples:staticvoid func(){}staticassert(isFunction!func);struct S{void func(){}}staticassert(isFunction!(S.func)); Detect whetherX is a final method or class.
Returns:true ifX is final,false otherwise
Examples:class C{void nf() {}staticvoid sf() {}finalvoid ff() {}}finalclass FC { }staticassert(!isFinal!(C));staticassert(isFinal!(FC));staticassert(!isFinal!(C.nf));staticassert(!isFinal!(C.sf));staticassert(isFinal!(C.ff)); Determines whether the typeS can be copied. If a type cannot be copied, then code such asMyStruct x; auto y = x; will fail to compile. Copying for structs can be disabled by using@disable this(this).
Returns:true ifS can be copied.false otherwise.
Examples:struct S1 {}// Fine. Can be copiedstruct S2 {this(this) {}}// Fine. Can be copiedstruct S3 {@disablethis(this); }// Not fine. Copying is disabled.struct S4 {S3 s;}// Not fine. A field has copying disabled.class C1 {}staticassert(isCopyable!S1);staticassert(isCopyable!S2);staticassert(!isCopyable!S3);staticassert(!isCopyable!S4);staticassert(isCopyable!C1);staticassert(isCopyable!int);staticassert(isCopyable!(int[])); template
DeducedParameterType(T)
template
DeducedParameterType(alias T)
The parameter type deduced by IFTI when an expression of type T is passed as an argument to a template function.
For all types other than pointer and slice types,DeducedParameterType!T is the same asT. For pointer and slice types, it isT with the outer-most layer of qualifiers dropped.