www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Template argument types

reply "bearophile" <bearophileHUGS lycos.com> writes:
Do you know why D templates accept floating point values and even 
arrays of 32 bit dchars:

template Foo(dchar[] s) {
     enum size_t Foo = s.length;
}
void main() {
     pragma(msg, Foo!("hello"d.dup));
}


But they don't accept arrays of ints?


template Foo(int[] s) {
     enum size_t Foo = s.length;
}
void main() {
     enum int[] a = [1, 2, 3];
     pragma(msg, Foo!a);
}


===>
test.d(1): Error: arithmetic/string type expected for 
value-parameter, not int[]


This works, but it's not the same thing:

template Foo(alias s) if (is(typeof(s) == int[])) {
     enum size_t Foo = s.length;
}
void main() {
     enum int[] a = [1, 2, 3];
     pragma(msg, Foo!a);
}

Bye and thank you,
bearophile
Jun 11 2012
parent =?UTF-8?B?QWxleCBSw7hubmUgUGV0ZXJzZW4=?= <alex lycus.org> writes:
On 12-06-2012 02:04, bearophile wrote:
 Do you know why D templates accept floating point values and even arrays
 of 32 bit dchars:

 template Foo(dchar[] s) {
 enum size_t Foo = s.length;
 }
 void main() {
 pragma(msg, Foo!("hello"d.dup));
 }


 But they don't accept arrays of ints?


 template Foo(int[] s) {
 enum size_t Foo = s.length;
 }
 void main() {
 enum int[] a = [1, 2, 3];
 pragma(msg, Foo!a);
 }


 ===>
 test.d(1): Error: arithmetic/string type expected for value-parameter,
 not int[]


 This works, but it's not the same thing:

 template Foo(alias s) if (is(typeof(s) == int[])) {
 enum size_t Foo = s.length;
 }
 void main() {
 enum int[] a = [1, 2, 3];
 pragma(msg, Foo!a);
 }

 Bye and thank you,
 bearophile
My guess is that dchar[] is special-cased in the compiler to allow passing strings. I think we should extend this to support arrays of all primitive types. -- Alex Rønne Petersen alex lycus.org http://lycus.org
Jun 11 2012