TypeTuple!(T...) vs Tuple!(T...)

Alex Parrill via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 2 07:07:17 PDT 2015


On Tuesday, 2 June 2015 at 08:10:27 UTC, rsw0x wrote:
> exactly what is the difference here?
>
> I have a rather large CTFE-generated TypeTuple in one of my 
> structs in my project, and I can seemingly replace it with a 
> Tuple with absolutely zero differences... except I compile 
> about 60-70% slower.
>
> The tuple page is even confusing me
> http://dlang.org/tuple.html
>
>>A variable declared with a TypeTuple becomes an ExpressionTuple:
>>alias TL = Tuple!(int, long);
>
> is it using Tuple!(T...) and TypeTuple!(T...) interchangeably?

Regular tuples are simply structs with a few methods like 
opIndex. Ex. `Tuple!(A,B,C)` is mostly equivalent to `struct { A 
_0; B _1; C _2; }`.

TypeTuples (whose name is IMO a misnomer) are special 
compile-time-only objects whose values are passed in the template 
parameters and can be types, aliases, or literal values. They 
aren't first-class types, and shouldn't be used as data storage, 
but they do have some unique properties that make them useful for 
metaprogramming.

Here's a small demonstration of TypeTuples:

	import std.stdio;
	import std.typetuple;

	void foo(int x, int y, int z) {
		writefln("x = %d, y = %d, z = %d", x, y, z);
	}

	void main() {
		int a, b, c;
		
		// Declare `vars` to be a typetuple containing aliases to a,b,c
		alias vars = TypeTuple!(a, b, c);
		
		vars[0] = 1; // Actually assign to a, b, c
		vars[1] = 2;
		vars[2] = 3;
		
		foo(a,b,c);
		foo(vars); // Same as above call
		
		alias test_values = TypeTuple!(123, 456, 789);
		foo(test_values); // Same as foo(123, 456, 7890)
		
		// won't work; test_values[0] is a literal and can't be 
assigned to.
		//test_values[0] = 321;
		
		foreach(ref some_var; vars) {
			// static foreach; this loop body is unrolled for each item in 
vars.
			some_var += 5;
		}
		
		foo(vars);
	}

Output:

$ rdmd ~/test.d
x = 1, y = 2, z = 3
x = 1, y = 2, z = 3
x = 123, y = 456, z = 789
x = 6, y = 7, z = 8


More information about the Digitalmars-d-learn mailing list