www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why does this template constraint not work?

reply "Ross Hays" <accounts rosshays.net> writes:
import std.stdio;

void test(T)()
	if (is (T : float))
{
	writeln(typeid(T));
}

void main()
{
	test!int;
}

When I run this I am getting the output "int"
My understanding of template constraints is that the call to 
test!int will not find a match since the function test only 
accepts float as a template parameter. I just ran into this 
problem while trying to understand something unrelated.
Dec 27 2013
parent reply "Ross Hays" <accounts rosshays.net> writes:
On Saturday, 28 December 2013 at 02:27:00 UTC, Ross Hays wrote:
 import std.stdio;

 void test(T)()
 	if (is (T : float))
 {
 	writeln(typeid(T));
 }

 void main()
 {
 	test!int;
 }

 When I run this I am getting the output "int"
 My understanding of template constraints is that the call to 
 test!int will not find a match since the function test only 
 accepts float as a template parameter. I just ran into this 
 problem while trying to understand something unrelated.
Okay figured it out actually. If you are not going to allow implicit conversion the appropriate constraint is... if (is (T == float)) I said it last time I asked about is and I will say it again. It is such a weird syntax...
Dec 27 2013
parent reply "Jonathan M Davis" <jmdavisProg gmx.com> writes:
On Saturday, December 28, 2013 02:31:56 Ross Hays wrote:
 Okay figured it out actually. If you are not going to allow
 implicit conversion the appropriate constraint is...
 
 if (is (T == float))
If you want to accept any floating point type but not implicit conversions, then use std.traits.isFloatingPoint.
 I said it last time I asked about is and I will say it again. It
 is such a weird syntax...
Heh. It works. And if you do a lot with template constraints, you'll get used to it. The main thing that avoids needing is expressions quite as much is std.traits, which can simplify many types of template constraints. - Jonathan M Davis
Dec 27 2013
parent "Ross Hays" <accounts rosshays.net> writes:
 If you want to accept any floating point type but not implicit 
 conversions,
 then use std.traits.isFloatingPoint.
Thank you that's good to know. Though for this particular example I was just making a basic demo of the problem.
Dec 27 2013