How to specify a template that uses unqualified type, like any normal function

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 15 07:24:57 PDT 2017


On 8/14/17 6:27 PM, Jonathan M Davis via Digitalmars-d-learn wrote:

> 
> As I understand it, sufficiently smart C++ compilers will figure out that
> the code for two template instantiations can be the same even if the types
> aren't, and they'll merge the definitions in the generated code, so you only
> really get one.
This isn't that problem.

I can define a function foo(int), which accepts all forms of int, and 
then *inside the function* I can mutate the parameter.

If I define foo as taking a template parameter T, then the 
implementations that accept just a straight int can modify the local 
copy of the parameter, but implementations that take a const(int) 
cannot. This means your function can't be the same for multiple 
instantiations. But there's no true limitation -- const(int) implicitly 
casts to int.

What IFTI would need is a mechanism to change the parameter types to 
mutable similar to how you can do this:

foo(T)(const(T) t);

This now generates one function for int, const(int), immutable(int), and 
t is const within the function.

What we need is something like:

foo(T)(mutable(T) t) // fictitious type constructor, doesn't work.

Or a more general mechanism to modify IFTI when it is deciding the 
parameters to use based on the call.

In my case, I've run into this when I'm trying to use short or ubyte, 
and someone uses literals:

void foo(short s) { ...}

void fooT(T)(T t) { foo(s); }

foo(1); // ok
fooT(1); // error.

It would be nice if there was some way to tell IFTI to infer T as short 
in this case.

-Steve


More information about the Digitalmars-d-learn mailing list