Template type deduction and specialization

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 20 02:38:41 PDT 2015


On Wednesday, May 20, 2015 07:36:21 Namespace via Digitalmars-d-learn wrote:
> What about:
> ----
> import std.stdio;
>
> void printVal(T)(T t) {
>      static if (is(T : U*, U))
>          printVal(*t);
>      else
>          writeln(t);
> }
>
> void main() {
>      int x = 100;
>      printVal(x);
>      int* px = &x;
>      printVal(px);
> }
> ----

That mostly works, but you it runs the classic risk of running into problems
with alias this (which is why checking for implicit conversions in static if
or template constraints is so incredibly dangerous if you're not _very_
careful). std.traits defines isPointer as follows:

enum bool isPointer(T) = is(T == U*, U) && !isAggregateType!T;

which avoids the alias this problem. Regardless, it's more idiomatic to just
use isPointer.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list