Function parameters from TypeTuple

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 17 12:03:41 PDT 2014


On Friday, 17 October 2014 at 17:57:58 UTC, Tofu Ninja wrote:
> On Friday, 17 October 2014 at 17:44:48 UTC, Tofu Ninja wrote:
>
> Not sure if what I wrote made sense, instead I will just post 
> the code that is vomiting on me...

You forgot the imports.

> template arrayType(T)
> {
> 	alias arrayType = T[];
> }
>
> template multiAccess(Args ...)
> {
> 	auto multiAccess(int i, staticMap!(arrayType, Args) args)
> 	{
> 		static if(args.length == 1) return Tuple!(args[0][i]);

`Tuple` is a type template. Use `tuple(foo, bar)` to build a
`Tuple!(typeof(foo), typeof(bar))`.

=> return tuple(args[0][i]);

> 		else return Tuple!(args[0][i], multiAccess!(Args[1 .. 
> $])(args[1 .. $]));

`Tuple!` -> `tuple` again. Also, `multiAccess` needs `i` again.
And you want to `expand` the sub-result into the tuple so that
it's flat.

=> return tuple(args[0][i], multiAccess!(Args[1 .. $])(i, args[1
.. $]).expand);

> 	}
> }
>
> void main(string[] args)
> {
> 	int[] a = [1,2];
> 	int[] b = [5,6];
> 	writeln(multiAccess!(int,int)(1, a,b));
> }
>
> but the compiler really does not like that at all... the error 
> message are very unhelpful as well...
>
> Generates 18 errors...
>
> main.d(52): Error: variable _param_1 cannot be read at compile 
> time
[...]

This is about you trying to instantiate `Tuple` with the runtime
value that is `args[0][1]`.

> main.d(52): Error: tuple index 0 exceeds length 0
[...]

I don't know where these come from. They don't show up for me.

> main.d(53): Error: template instance main.multiAccess!() error 
> instantiating
[...]

These are due to previous errors.


For style points you could

* Use the short form for function templates:

      auto multiAccess(Args ...)(int i, staticMap!(arrayType, Args)
args) {...}

* Take array types as template arguments instead of constructing
them. This allows them to be inferred (IFTI - Implicit Function
Template Instantiation):

      auto multiAccess(Args ...)(int i, Args args)
          /* Maybe put a template constraint here that forces Args
to be all arrays. */
      {
          import std.typecons: tuple;
          static if(args.length == 1) return tuple(args[0][i]);
          else return tuple(args[0][i], multiAccess(i, args[1 ..
$]).expand);
      }
      void main()
      {
          int[] a = [1,2];
          int[] b = [5,6];
          import std.stdio;
          writeln(multiAccess(1, a,b));
      }


More information about the Digitalmars-d-learn mailing list