首页 > 其他 > 详细

泛型术语:占位类型placeholder

时间:2018-10-08 22:47:09      阅读:147      评论:0      收藏:0      [点我收藏+]

 

Here’s a generic version of the same code:

  1. struct Stack<Element> {
  2. var items = [Element]()
  3. mutating func push(_ item: Element) {
  4. items.append(item)
  5. }
  6. mutating func pop() -> Element {
  7. return items.removeLast()
  8. }
  9. }

Note how the generic version of Stack is essentially the same as the nongeneric version, but with a type parameter called Element instead of an actual type of Int. This type parameter is written within a pair of angle brackets (<Element>) immediately after the structure’s name.

Element defines a placeholder name for a type to be provided later. This future type can be referred to as Element anywhere within the structure’s definition. In this case, Element is used as a placeholder in three places:

  • To create a property called items, which is initialized with an empty array of values of type Element
  • To specify that the push(_:) method has a single parameter called item, which must be of type Element
  • To specify that the value returned by the pop() method will be a value of type Element

https://docs.swift.org/swift-book/LanguageGuide/Generics.html

 

Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.

template<typename T>
class List
{
   /* class contents */
};

List<Animal> list_of_animals;
List<Car> list_of_cars;

Above, T is a placeholder for whatever type is specified when the list is created.

 

https://en.wikipedia.org/wiki/Generic_programming

泛型术语:占位类型placeholder

原文:https://www.cnblogs.com/feng9exe/p/9757568.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!