Check for presence of function
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Mar 23 05:55:18 PDT 2014
On Sun, Mar 23, 2014 at 1:40 PM, Steve Teale
<steve.teale at britseyeview.com> wrote:
> What's the cool/idiomatic D way to test at compile time if a struct has a
> member function with a particular signature? Along the lines of:
>
> struct Unrelated
> {
> ...
> }
>
> template isSomething(T)
> {
> enum bool isSomething = is(typeof(
> (inout int = 0)
> {
> T???; // has a function void doSomething(Unrelated* up);
> // etc
> }));
> }
>
> struct Thingie
> {
> ...
> }
>
> static assert(isSomething!(Thingie));
You can use __traits(compiles, /* some code */), like this:
struct Unrelated {}
template isSomething(T)
{
enum bool isSomething = __traits(compiles,
{
Unrelated* up;
T.init.doSomething(up);
}
);
}
struct Thingie
{
void doSomething(Unrelated* up) {}
}
void main()
{
pragma(msg, isSomething!Thingie); // true
pragma(msg, isSomething!Unrelated); // false
pragma(msg, isSomething!int); // false
}
More information about the Digitalmars-d-learn
mailing list