digitalmars.D.learn - limiting templates
- BCS (6/6) May 01 2007 I have a template
- Daniel Keep (31/41) May 01 2007 Not one that I can think of off the top of my head. The problem is that
- BCS (15/31) May 01 2007 Am I not understanding you correctly, I thought this worked (it did the ...
I have a template int Foo(T)(T bar); I want to be able to call it like this: foo("hello"); and have T end up as char[] not char[5]. Is there any way to limit the template to that?
May 01 2007
BCS wrote:I have a template int Foo(T)(T bar); I want to be able to call it like this: foo("hello"); and have T end up as char[] not char[5]. Is there any way to limit the template to that?Not one that I can think of off the top of my head. The problem is that you can't specialise templated functions. That said, you might be able to do something like this (note: untested, off the top of my head code): template Foo(T) { static if( IsStaticArray!(T) ) alias Foo!(DynamicArrayFromStaticArray!(T)) Foo; else int Foo(T bar) { ... } } Obviously, you'd have to write IsStaticArray and DynamicArrayFromStaticArray (unless they're in std.traits). The other thing you can do is ensure the argument is really a char[] in the first place: foo("hello"[]); The [] does a slice of the char[5], which results in a char[]. -- Daniel -- int getRandomNumber() { return 4; // chosen by fair dice roll. // guaranteed to be random. } http://xkcd.com/ v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
May 01 2007
Reply to Daniel,BCS wrote:Am I not understanding you correctly, I thought this worked (it did the last time I checked) int bar(char[] s: "hello")() { return s.length; } I though of that, but what I going for is code folding to reduce duplication. I just though of what to do int FooT(T)(T bar); alias FooT!(char[]) Foo; alias FooT!(int) Foo; this works because I have a finite list of type that are to be allowed. The "good" way to do it would be to allow for limiting rules to be applied: int foo(T : is(T[]) || !is(T.length)]) ;I have a template int Foo(T)(T bar); I want to be able to call it like this: foo("hello"); and have T end up as char[] not char[5]. Is there any way to limit the template to that?Not one that I can think of off the top of my head. The problem is that you can't specialise templated functions.
May 01 2007