www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Array literal template parameter?

reply "Maxime Chevalier" <maximechevalierb gmail.com> writes:
I need to pass an array literal as a template parameter. The 
reference on this website seems to imply this is possible, but 
doesn't illustrate it. The obvious way doesn't seem to work:

mixin template MyTemplate(int[] arr) {}
Error: arithmetic/string type expected for value-parameter, not 
int[]

Is there no way to do this without using a mixin and CTFE? I 
don't think I can use tuple types because I need to initialize a 
struct member using the array literal parameter.
Nov 20 2012
next sibling parent Timon Gehr <timon.gehr gmx.ch> writes:
On 11/21/2012 12:22 AM, Maxime Chevalier wrote:
 I need to pass an array literal as a template parameter. The reference
 on this website seems to imply this is possible, but doesn't illustrate
 it. The obvious way doesn't seem to work:

 mixin template MyTemplate(int[] arr) {}
 Error: arithmetic/string type expected for value-parameter, not int[]

 Is there no way to do this without using a mixin and CTFE? I don't think
 I can use tuple types because I need to initialize a struct member using
 the array literal parameter.
I guess it should work, and this is a compiler bug. You can work around the limitation by using a template alias parameter.
Nov 20 2012
prev sibling next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Maxime Chevalier:

 I need to pass an array literal as a template parameter. The 
 reference on this website seems to imply this is possible, but 
 doesn't illustrate it. The obvious way doesn't seem to work:
It's a known compiler bug, already in Bugzilla. In the meantime this is a workaround: template Foo(Args...) if (Args.length == 1) { pragma(msg, Args[0]); enum Foo = Args; } void main() { enum double[] a = [10, 20, 30]; auto x = Foo!a; } Bye, bearophile
Nov 20 2012
prev sibling parent Jacob Carlborg <doob me.com> writes:
On 2012-11-21 00:22, Maxime Chevalier wrote:
 I need to pass an array literal as a template parameter. The reference
 on this website seems to imply this is possible, but doesn't illustrate
 it. The obvious way doesn't seem to work:

 mixin template MyTemplate(int[] arr) {}
 Error: arithmetic/string type expected for value-parameter, not int[]

 Is there no way to do this without using a mixin and CTFE? I don't think
 I can use tuple types because I need to initialize a struct member using
 the array literal parameter.
It seems an "alias" parameter is working: mixin template MyTemplate(alias arr) {} You might want to add some kind of template constraint on that. -- /Jacob Carlborg
Nov 20 2012