Template specialization
Darrell Gallion via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 22 07:41:10 PST 2016
On Friday, 22 January 2016 at 13:03:52 UTC, Darrell Gallion wrote:
> On Friday, 22 January 2016 at 11:23:56 UTC, Marc Schütz wrote:
>> On Friday, 22 January 2016 at 01:33:42 UTC, Darrell Gallion
>> wrote:
>>> void foo(A)()
>>> if (!is (A == int)) {
>>> pragma(msg, "int");
>>> }
>>>
>>> void foo(A)()
>>> if (is (A == int[])) {
>>> pragma(msg, "int[]");
>>> }
>>>
>>> void main() {
>>>
>>> foo!(int)();
>>> foo!(int[])();
>>> }
>>>
>>> ===========
>>>
>>> source\app.d(15): Error: template app.foo cannot deduce
>>> function from argument types !(int)(), candidates are:
>>> source\app.d(3): app.foo(A)() if (!is(A == int))
>>> source\app.d(8): app.foo(A)() if (is(A == int[]))
>>> source\app.d(16): Error: app.foo called with argument types
>>> () matches both:
>>> source\app.d(3): app.foo!(int[]).foo()
>>> and:
>>> source\app.d(8): app.foo!(int[]).foo()
>>
>> Have a look at the first template constraint. It checks
>> whether the template parameter _is not_ `int`, so of course,
>> the first instantiation fails, and the second one is ambiguous.
>
> I'm aware this doesn't look right or compile.
> How do I do this?
>
>
> void foo(int x)
> { }
>
> void foo(int [] x)
> { }
>
> template foo(T)(T x){}
>
> void main() {
> int x;
> int [] a;
> foo((x);
> foo(a);
> foo("hi");
> }
What was getting me...
Defining the templates within another function, fails.
void main(){
long foo(T: int)(T t)
{
return cast(long)t;
}
long[] foo(T: int[])(T t)
{ long [] ar;
return ar;
}
T foo(T)(T t)
{ return t; }
foo(1);
foo([1,2]);
foo("hi");
}
source/app.d(224,3): Error: declaration foo(T : int[])(T t) is
already defined
source/app.d(229,3): Error: declaration foo(T)(T t) is already
defined
source/app.d(236,6): Error: template D main.foo cannot deduce
function from argument types !()(int[]), candidates are:
source/app.d(219,8): app.main.foo(T : int)(T t)
source/app.d(237,6): Error: template D main.foo cannot deduce
function from argument types !()(string), candidates are:
source/app.d(219,8): app.main.foo(T : int)(T t)
More information about the Digitalmars-d-learn
mailing list