Is there a traits to check if a type has value semantics or not?
There is no trait for value types, at least not in the documentation However, I have checked for value types before using the "is expression":
import std.stdio;
struct Foo {}
auto fn(T)(T type)
{
static if (is(T == struct)) {
writeln(T.stringof ~ " is a value type");
} else if (is(T == class)) {
writeln(T.stringof ~ " is a reference type");
} else {
writeln(T.stringof ~ " is something else");
}
}
void main()
{
Foo f;
fn(f);
fn(new Object());
fn(1);
}
Also is there a trait to check if a type supports a specific operation such as bitwise and &?
Other than the trait for compiles, this can also be achieved with an is expression. This is similar to how it is currently done for ranges, for example:
import std.stdio;
struct Foo {
auto opBinary(string op)(Foo rhs)
if (op == "&")
{
return rhs.init; // dummy implementation
}
};
template canUseBitOps(T)
{
enum bool canUseBitOps = is(typeof(
(inout int = 0)
{
T t1 = T.init;
T t2 = T.init;
auto r = t1 & t2;
}));
}
void main()
{
assert(canUseBitOps!int);
assert(!canUseBitOps!string);
assert(canUseBitOps!Foo);
}