Templates array detection
Cube
sq at ua.re
Wed Dec 12 06:04:59 PST 2012
On Wednesday, 12 December 2012 at 12:34:34 UTC, bearophile wrote:
> Cube:
>
>> I'm having a problem getting templates to work correctly.
>> I want to handle arrays differently, but when I try to compile
>> the following example code it says it matches more than 1
>> template. What is the correct way to do this?
>>
>>
>> --
>> void main()
>> {
>> foo(1);
>> foo([1,1]);
>> }
>>
>> void foo(T)(T t)
>> {
>> writeln(t);
>> }
>>
>> void foo(T)(T[] t)
>> {
>> for(int i = 0; i < t.length; i++)
>> writeln(t[i]);
>> }
>> --
>
> In general D templates refuse ambiguity. So to fix your
> situation you have to state that the T in your first foo
> overload is not an array:
>
> import std.stdio, std.traits;
>
> void main()
> {
> foo(1);
> foo([1, 1]);
> }
>
> void foo(T)(T t) if (!isArray!T)
> {
> writeln(t);
> }
>
> void foo(T)(T[] t)
> {
> foreach (ti; t)
> writeln(ti);
> }
>
>
> Bye,
> bearophile
Hi,
I eventually modified my code to:
--
void main()
{
foo(1);
foo([1,1]);
}
void foo(T)(T t)
{
bar!(T)(t);
}
void bar(T)(T t)
{
writeln(t+1);
}
void bar(T: T[])(T[] t)
{
for(int i = 0; i < t.length; i++)
writeln(t[i]);
}
--
Essentially I added a helper function that added !(T).
What, if any, is the benefit of either approach?
And a similar issue, what if I have a struct:
--
struct Data(T)
{
int elem = 3;
}
void main()
{
foo(1);
foo([1,1]);
foo(new Data!(int));
foo(new Data!(float));
}
void foo(T)(T t)
{
bar!(T)(t);
}
void bar(T)(T t)
{
writeln(t+1);
}
void bar(T: T[])(T[] t)
{
for(int i = 0; i < t.length; i++)
writeln(t[i]);
}
--
And I want to add this to the rest of the program. Where/how can
I direct the Data's to separate functions?
Thanks :)
More information about the Digitalmars-d-learn
mailing list