Places a TypeTuple can be used
Jonathan M Davis
jmdavisProg at gmx.com
Thu Aug 15 23:18:21 PDT 2013
On Thursday, August 15, 2013 21:14:03 Ali Çehreli wrote:
> I know of three places a TypeTuple can be used at:
>
> 1) Function parameter list
>
> 2) Template parameter list
>
> 3) Array literal element list
>
> Are there more?
>
> import std.typetuple;
>
> void foo(int, string, double)
> {}
>
> struct S(T, float f)
> {}
>
> void main()
> {
> // 1) Function parameter list: May not contain types
> foo(TypeTuple!(42, "hello", 1.5));
>
> // 2) Template parameter list: May contain types
> auto s = S!(TypeTuple!(char, 2.5))();
>
> // 3) Array elements: Elements must be the same type
> auto a = [ TypeTuple!(1, 2, 3, 4) ];
>
> // Are there other places that a TypeTuple can be used?
> }
It can be used in foreach, which essentially makes it a static foreach. This
is extremely useful when unit testing. e.g.
foreach(T; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
assert(stripLeft(to!T(" foo ")) == to!T("foo "));
}
The code within the foreach is duplicated, because the loop is run at compile
time. So, the above code becomes something like
{assert(stripLeft(to!(char[])(" foo ")) == to!(char[])("foo "));}
{assert(stripLeft(to!(wchar[])(" foo ")) == to!(wchar[])("foo "));}
{assert(stripLeft(to!(dchar[])(" foo ")) == to!(dchar[])("foo "));}
{assert(stripLeft(to!string(" foo ")) == to!string("foo "));}
{assert(stripLeft(to!wstring(" foo ")) == to!wstring("foo "));}
{assert(stripLeft(to!dstring(" foo ")) == to!dstring("foo "));}
You can use TypeTuple in enums, though the enum value would have to be used in
a context that TypeTuples can be used in. You can also alias them.
There are probably others, especially when you start messing with templates
and parameter lists, but while those use the built-in tuples which TypeTuple
aliases, I can't think of any case at the moment where you would explicitly
use TypeTuple.
You should probably read this article if you haven't:
http://dlang.org/tuple.html
Unfortunately, it muddles things a fair bit, because it uses Tuple instead of
std.typetuple.TypeTuple, and then it talks about expression tuples vs type
tuples (whereas a TypeTuple could be either an expression tuple or a type
tuple), but that just highlights how confusing this is and how badly named
TypeTuple is (but unfortunately, it's used in so much code now, that renaming
it just isn't going to happen). That article should probably be rewritten so
that it takes TypeTuple into account. But it does contain some good info if
you can properly understand the difference between TypeTuple and a type tuple.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list