Template specialization using traits?

tcak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 21 03:18:01 PST 2015


On Monday, 21 December 2015 at 11:12:10 UTC, Jonathan M Davis 
wrote:
> On Monday, 21 December 2015 at 11:07:16 UTC, Jonathan M Davis 
> wrote:
>> For your example to work with template constraints, the most 
>> straightforward solution would be
>>
>> void func(T)(T t)
>>     if(!isIntegral!T)
>> {
>>     writeln(1);
>> }
>>
>> void func(T)(T t)
>>     if(isIntegral!T)
>> {
>>     writeln(2);
>> }
>
> Alternatively, you can use static if, though you're only 
> dealing with one template in that case. e.g.
>
> void func(T)(T t)
> {
>     static if(isIntegral!T)
>         writeln(2);
>     else
>         writeln(1);
> }
>
> - Jonathan M Davis

Another alternative is:

template func(T){
	static if( isIntegral!T ){
		void func(T t){
			writeln( 2 );
		}
	}
	else{
		void func(T t){
			writeln( 1 );
		}
	}
}


More information about the Digitalmars-d-learn mailing list