D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 3197 - Minor fixes and additions to std.traits
Summary: Minor fixes and additions to std.traits
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: Andrei Alexandrescu
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2009-07-21 03:50 UTC by Lars T. Kyllingstad
Modified: 2015-06-09 05:13 UTC (History)
1 user (show)

See Also:


Attachments
Patch for traits.d (svn rev. 1242) (2.15 KB, patch)
2009-07-21 03:50 UTC, Lars T. Kyllingstad
Details | Diff

Note You need to log in before you can comment on or make changes to this issue.
Description Lars T. Kyllingstad 2009-07-21 03:50:47 UTC
Created attachment 430 [details]
Patch for traits.d (svn rev. 1242)

These are just some small fixes and additions to std.traits that I've found useful, and I would very much like to see them included in Phobos.

Firstly, I've attached a patch against traits.d (svn rev. 1242) which does the following:

 - Made ParameterTypeTuple work with structs/classes with opCall.
   Updated doc comment to reflect this and added unittest.

 - I've changed the code of ReturnType so that the "argument has
   no return type" error is emitted instead of just a template
   instantiation failure whenever a struct/class without an opCall
   is given as the argument.


Secondly, here are two things I'd like to see in std.traits:


/** Get the type of the elements of an array.
 *  Example:
 *  ---
 *  int[][] foo;
 *  ElementType!foo bar;    // bar is declared as int (not int[])
 *  ---
 */
template ElementType(alias dg)
{
    alias ElementType!(typeof(dg)) ElementType;
}

/// ditto
template ElementType(T : T[])
{
    alias ElementType!T ElementType;
}

template ElementType(T)
{
    alias T ElementType;
}

unittest
{
    static assert (is(ElementType!(int[]) == int));
    real[][] foo;
    static assert (is(ElementType!foo == real));
}



/** Detect whether T is a callable type, i.e. a function,
 *  a pointer to a function, a delegate, a struct with an opCall,
 *  a pointer to a struct with an opCall, or a class with
 *  an opCall.
 */
template isCallable(T)
{
    static if (is(T == return))
        enum isCallable = true;
    else static if (is(typeof(&T.opCall) == return))
        enum isCallable = true;
    else
        enum isCallable = false;
}

unittest
{
    static assert (isCallable!(int delegate()));

    struct Bar { int opCall() { return 0; } }
    static assert (isCallable!Bar);

    static assert (!isCallable!int);
}
Comment 1 Andrei Alexandrescu 2009-07-21 08:38:22 UTC
Thanks!
Comment 2 Andrei Alexandrescu 2009-08-28 08:53:09 UTC
Integrated patch, thanks.