D 语言 - 元组
元组用于将多个值组合为单个对象。 元组包含一系列元素。 元素可以是类型、表达式或别名。 元组的数量和元素在编译时是固定的,并且不能在运行时更改。
元组同时具有结构体和数组的特征。 元组元素可以是不同类型,例如结构。 可以通过像数组一样的索引来访问元素。 它们由 std.typecons 模块中的 Tuple 模板实现为库功能。 Tuple 使用 std.typetuple 模块中的 TypeTuple 进行某些操作。
使用 tuple() 的元组
元组可以通过函数 tuple() 来构造。 元组的成员通过索引值访问。 下面显示了一个示例。
示例
import std.stdio;
import std.typecons;
void main() {
auto myTuple = tuple(1, "Tuts");
writeln(myTuple);
writeln(myTuple[0]);
writeln(myTuple[1]);
}
当上面的代码被编译并执行时,会产生以下结果 −
Tuple!(int, string)(1, "Tuts") 1 Tuts
使用元组模板的元组
元组也可以直接通过元组模板而不是tuple()函数来构造。 每个成员的类型和名称被指定为两个连续的模板参数。 使用模板创建时可以通过属性访问成员。
import std.stdio;
import std.typecons;
void main() {
auto myTuple = Tuple!(int, "id",string, "value")(1, "Tuts");
writeln(myTuple);
writeln("by index 0 : ", myTuple[0]);
writeln("by .id : ", myTuple.id);
writeln("by index 1 : ", myTuple[1]);
writeln("by .value ", myTuple.value);
}
当上面的代码被编译并执行时,会产生以下结果
Tuple!(int, "id", string, "value")(1, "Tuts") by index 0 : 1 by .id : 1 by index 1 : Tuts by .value Tuts
扩展属性和函数参数
元组的成员可以通过 .expand 属性或切片来扩展。 该扩展/切片值可以作为函数参数列表传递。 下面显示了一个示例。
示例
import std.stdio;
import std.typecons;
void method1(int a, string b, float c, char d) {
writeln("method 1 ",a,"\t",b,"\t",c,"\t",d);
}
void method2(int a, float b, char c) {
writeln("method 2 ",a,"\t",b,"\t",c);
}
void main() {
auto myTuple = tuple(5, "my string", 3.3, 'r');
writeln("method1 call 1");
method1(myTuple[]);
writeln("method1 call 2");
method1(myTuple.expand);
writeln("method2 call 1");
method2(myTuple[0], myTuple[$-2..$]);
}
当上面的代码被编译并执行时,会产生以下结果 −
method1 call 1 method 1 5 my string 3.3 r method1 call 2 method 1 5 my string 3.3 r method2 call 1 method 2 5 3.3 r
TypeTuple
TypeTuple 在 std.typetuple 模块中定义。 是以逗号分隔的值和类型列表。 下面给出了一个使用 TypeTuple 的简单示例。 TypeTuple 用于创建参数列表、模板列表和数组文字列表。
import std.stdio;
import std.typecons;
import std.typetuple;
alias TypeTuple!(int, long) TL;
void method1(int a, string b, float c, char d) {
writeln("method 1 ",a,"\t",b,"\t",c,"\t",d);
}
void method2(TL tl) {
writeln(tl[0],"\t", tl[1] );
}
void main() {
auto arguments = TypeTuple!(5, "my string", 3.3,'r');
method1(arguments);
method2(5, 6L);
}
当上面的代码被编译并执行时,会产生以下结果 −
method 1 5 my string 3.3 r 5 6

