www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Determining if a symbol is a function

reply Doctor J <nobody nowhere.com> writes:
I want to test whether a struct member is a real field or a property at compile
time.  I thought this is what is(type == function) is supposed to do, but I
can't find anything that will make is(type == function) true.  What am I doing
wrong?

----------------------------------------------
import std.stdio;

int func0()
{
    return 0;
}

int func1(int x)
{
    return x;
}

int main()
{
    static if (is(func0))
        writefln("func0 is semantically correct.");
    static if (is(func0 == function))
        writefln("func0 is a function.");
    else
        writefln("func0 is NOT a function.");
    writefln("typeof(func0): %s\n", typeof(func0).stringof);
    
    static if (is (func0()))
        writefln("func0() is semantically correct.");
    static if (is(func0() == function))
        writefln("func0() is a function.");
    else
        writefln("func0() is NOT a function.");
    writefln("typeof(func0()): %s", typeof(func0()).stringof);
    
    // And for good measure, this one doesn't even compile; why is that?
    // writefln("typeof(func1): %s", typeof(func1).stringof);   
    return 0;
}
------------------------------------------

This outputs:

func0 is NOT a function.
typeof(func0): (int())()

func0() is NOT a function.
typeof(func0()): int



Oh, and I'm using Phobos 1.0 with gdc.  :)
Apr 12 2009
parent reply Doctor J <nobody nowhere.com> writes:
Answered my own question:

    static if (is(typeof(func0) == function))
        writefln("func0 is a function.");

is() really wants a type, not an expression.
Apr 12 2009
next sibling parent bearophile <bearophileHUGS lycos.com> writes:
Doctor J:
     static if (is(typeof(func0) == function))
         writefln("func0 is a function.");
 is() really wants a type, not an expression.
What you may want is to test if a type is a callable (function, delegate or object with opCall). See IsCallable here: http://www.fantascienza.net/leonardo/so/dlibs/templates.html Bye, bearophile
Apr 12 2009
prev sibling parent Lars Kyllingstad <public kyllingen.NOSPAMnet> writes:
Doctor J wrote:
 Answered my own question:
 
     static if (is(typeof(func0) == function))
         writefln("func0 is a function.");
 
 is() really wants a type, not an expression.
You say you want to test whether a struct/class member is a field or a property. Pointers to class and struct methods are delegates, not function pointers. http://www.digitalmars.com/d/1.0/type.html#delegates So the correct thing to write would be: static if (is(typeof(func0) == delegate)) { ... } or, to test whether func0 is a function OR a delegate, static if (is(typeof(func0) == return)) { ... } For details, see http://www.digitalmars.com/d/1.0/expression.html#IsExpression -Lars
Apr 13 2009