Compare TypeTuple element with another type
Rene Zwanenburg via Digitalmars-d
digitalmars-d at puremagic.com
Fri Aug 1 07:03:55 PDT 2014
On Friday, 1 August 2014 at 11:55:02 UTC, Tudor Berariu wrote:
> On Friday, 1 August 2014 at 10:34:02 UTC, Rene Zwanenburg wrote:
>> On Friday, 1 August 2014 at 10:25:39 UTC, Tudor Berariu wrote:
>>> Is it possible to compare at compile time an element from a
>>> TypeTuple with another type?
>>>
>>> This code fails:
>>>
>>> alias T = Tuple!(int, bool);
>>> static assert(is(T[0] == int));
>>>
>>>
>>> Error: static assert (is(Tuple!(int, bool)[0] == int)) is
>>> false
>>>
>>>
>>> Tudor
>>
>> Tuple is not a type tuple, it's a runtime tuple. TypeTuple is
>> located in std.typetuple. Use that and your code will work.
>
> Thank you! That works indeed, but my problem is actually a bit
> different.
> I called that a "TypeTuple" because I read this line in the
> documentation "If a tuple's elements are solely types, it is
> called a TypeTuple" (http://dlang.org/tuple.html).
>
> What I want to achieve is something like this:
>
> template isNeededType(T) {
> enum bool isNeededType = is(T[0] == int);
> }
>
> ...
>
> enum auto t = Tuple!(int, bool)(3, false);
> alias T = typeof(t);
> static assert(isNeededType!T);
>
> I know that "is(typeof(t[0]) == int)" works for the above
> example, but I need to get, if possible, the types of the
> elements from the type of that tuple only.
In addition to what John Colvin posted, I'd like to add that user
defined types have a 'tupleof' property. (This is yet another
kind of tuple, sigh).
An example:
struct S1
{
int i;
string s;
}
struct S2
{
int someInt;
string someString;
}
void main()
{
// A foreach loop over these kind of tuples is always expanded
during
// compilation due to their nature
foreach(T; typeof(S1.tupleof))
{
// Here 'T' _is_ a type, not an instance of a type
pragma(msg, T); // Will print 'int' and 'string' during
compilation
}
S1 s1;
S2 s2;
// A way to copy one struct's values over to another of a
different type,
// but with the same layout:
foreach(i, value; s1.tupleof)
{
s2.tupleof[i] = value;
}
}
More information about the Digitalmars-d
mailing list