Check template parameter whether it has "length"

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Oct 8 04:42:45 PDT 2015


On Thursday, 8 October 2015 at 09:29:30 UTC, tcak wrote:
> I am "trying" to write a function that takes an array of items, 
> and returns the length of longest item.
>
> [code]
> size_t maxLength(A)( const A[] listOfString ) if( __traits( 
> hasMember, A, "length" ) )
> {
> 	return 0; // not implemented yet
> }
> [/code]
>
> I tried it with
>
> if( __traits( compiles, A.length ) )
>
> as well. But compiler doesn't match it.
>
> writeln("Max Length: ", maxLength( ["foo", "123456789"] ));
>
> Compilers says it cannot deduce function from argument types ...
>
> I do not want to check whether the type "A" is string, char[], 
> etc. As long as it has length (please do not put me into 
> ranges, library functions etc as much as possible), I want the 
> function to accept it.

iirc there's a hasLength trait in std.traits e.g. static 
assert(hasLength!int[])


More information about the Digitalmars-d-learn mailing list