Error with constraints on a templated fuction

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 25 09:52:18 PDT 2014


On Mon, 25 Aug 2014 15:48:10 +0000
Jeremy DeHaan via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> wrote:

> I've done things like this before with traits and I figured that
> this way should work as well, but it gives me errors instead.
> Perhaps someone can point out my flaws.
>
> immutable(T)[] toString(T)(const(T)* str)
>   if(typeof(T) is dchar)//this is where the error is
> {
>   return str[0..strlen(str)].idup; //I have strlen defined for
> each *string
> }
>
> I was going to add some || sections for the other string types,
> but this one won't even compile.
>
> src/dsfml/system/string.d(34): Error: found ')' when expecting
> '.' following dchar
> src/dsfml/system/string.d(35): Error: found '{' when expecting
> identifier following 'dchar.'
> src/dsfml/system/string.d(36): Error: found 'return' when
> expecting ')'
> src/dsfml/system/string.d(36): Error: semicolon expected
> following function declaration
> src/dsfml/system/string.d(36): Error: no identifier for
> declarator str[0 .. strlen(str)]
> src/dsfml/system/string.d(36): Error: no identifier for
> declarator .idup
> src/dsfml/system/string.d(37): Error: unrecognized declaration
>
>
> It compiles if I remove the 'if(typeof(T) is dchar)' section. Any
> thoughts?

As the others have pointed out, you need to do is(T == dchar). The way you
used is the is operator and it checks for bitwise equality (most frequently
used for comparing pointers), and it's a runtime operation, whereas the is
that you need to use in a template constraint is an is expression, which is a
compile time operation:

http://dlang.org/expression.html#IsExpression

is expressions actually get pretty complicated in their various forms, but the
most basic two are probably is(T == dchar), which checks that the two types ar
the same, and is(T : dchar), which checks that T implictly converts to dchar.
Another commonly used one is is(typeof(foo)). typeof(foo) gets the type of foo
and will result in void if foo doesn't exist, and is(void) is false, whereas
is(someOtherType) is true, so it's frequently used to check whether something
is valid. The Phobos source code is littered with examples (especially in
std.algorithm, std.range, and std.traits), since is expressions are frequently
used in template constraints.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list