Meta
Meta

Reputation: 1111

Detecting if a Callable is Static

I thought I would be able to do this with std.traits.functionAttributes, but it does not support static. For any type of callable (structs with opCall included), how can I tell if that callable is annotated with static? For example:

template isStaticCallable(alias fun) if (isCallable!fun)
{
    enum isStaticCallable = ...?
}

Upvotes: 3

Views: 72

Answers (1)

yaz
yaz

Reputation: 1330

Traits are part of dlang which provide insight into compile time information. One of the available traits is isStaticFunction used as __traits(isStaticFunction, fun).

Example code:

import std.traits;

template isStaticCallable(alias fun) if (isCallable!fun)
{
    enum isStaticCallable = __traits(isStaticFunction, fun);
}


void main() {}

class Foo
{
    static void boo() {}
    void zoo() {}
}

pragma(msg, isStaticCallable!main); // note that this prints true because
                                    // the function has no context pointer
pragma(msg, isStaticCallable!(Foo.boo)); // prints true
pragma(msg, isStaticCallable!(Foo.zoo)); // prints false

Upvotes: 4

Related Questions