Thread overview | |||||
---|---|---|---|---|---|
|
May 01, 2007 limiting templates | ||||
---|---|---|---|---|
| ||||
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 Re: limiting templates | ||||
---|---|---|---|---|
| ||||
Posted in reply to BCS | 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 02, 2007 Re: limiting templates | ||||
---|---|---|---|---|
| ||||
Posted in reply to Daniel Keep | Reply to Daniel,
> 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.
>
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)]) ;
|
Copyright © 1999-2021 by the D Language Foundation