simple (I think) eponymous template question ... what is proper idimatic way ?
Tejas
notrealemail at gmail.com
Wed Aug 18 06:53:51 UTC 2021
On Wednesday, 18 August 2021 at 05:33:13 UTC, james.p.leblanc
wrote:
> On Tuesday, 17 August 2021 at 20:28:20 UTC, Alexandru Ermicioi
> wrote:
>> On Tuesday, 17 August 2021 at 19:53:52 UTC, james.p.leblanc
>> wrote:
>>>
>>> Wow! That is absolutely beautiful ... I had never seen (or
>>> even
>>> imagined) a recursive template! This expands my mind in a
>>> good
>>> way ... and is going into my toolbox immediately.
>>>
>>> Best Regards,
>>> James
>>
>> Just don't over rely on it. It can cause compilation
>> slowdowns, so avoid it if you can.
>
> I've been happily trying to absorb all the helpful concepts
> posted.
>
> A final related question in the quest for simplicity and
> robustness.
>
> If I wanted to ensure that a function accepts only arguments of
> byte, int, uint, long, etc. (i.e. integer-like types). Is the
> accepted
> way to do this like so?:
>
> **auto foo( T : long )(T a, T b){ ... }**
>
> I really wish I could find a good explanation of the ":" (colon)
> used in templates. I am sure one exists ...but haven't come
> upon
> it just yet.
>
> (I thought "isIntegral" in traits module would be helpful...but
> I failed in my experiments.)
>
> Thanks for patience with this question!
>
> Best Regards,
> James
A template specialization is basically a template overload.
For example:
```d
void func(int a){
writeln("argument is integer");
}
void func(long a){
writeln("argument is long");
}
void main(){
int a;
long b;
func(a);
func(b);
}
```
The above does what you expect.
Now the template specialization way:
```d
void funcTemplate(T:int)(T a){
writeln("argument is int");
}
void funcTemplate(T : long)(T a){
writeln("argument is long");
}
void main(){
int c;
long d;
funcTemplate(c);
funcTemplate(d);
}
```
The above will also do what you expect.
Template specialization is basically overloading for templates,
nothing more.
Below is a complete working copy-paste example combining both:
```d
import std;
void func(int a){
writeln("argument is integer");
}
void func(long a){
writeln("argument is long");
}
void funcTemplate(T:int)(T a){
writeln("argument is int");
}
void funcTemplate(T : long)(T a){
writeln("argument is long integer");
}
void main(){
int a;
long b;
func(a);
func(b);
funcTemplate(a);
funcTemplate(b);
}
```
More information about the Digitalmars-d-learn
mailing list