目录

D编程 - 元组(Tuples)

元组用于将多个值组合为单个对象。 元组包含一系列元素。 元素可以是类型,表达式或别名。 元组的数量和元素在编译时是固定的,在运行时不能更改。

元组具有结构和数组的特征。 元组元素可以是不同类型的结构。 可以通过像数组一样的索引来访问元素。 它们由std.typecons模块中的Tuple模板实现为库特征。 Tuple使用std.typetuple模块中的TypeTuple进行某些操作。

Tuple Using tuple()

元组可以通过函数tuple()构造。 通过索引值访问元组的成员。 一个例子如下所示。

例子 (Example)

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模板而不是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属性或切片来扩展Tuple的成员。 此扩展/切片值可以作为函数参数列表传递。 一个例子如下所示。

例子 (Example)

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
↑回到顶部↑
WIKI教程 @2018