2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

型引数の制約によるオーバーロード

Last updated at Posted at 2015-01-01

(Swift 1.1, 2.1 で確認済み)

SwiftのcountElements()を自前で実装する(or C++のSTLのような総称的な操作を行う)でサラっと触れましたが、Swiftでは型引数の制約(constraint)が違うとオーバーロードできるようです。典型的な使い方は、まさに件のエントリで触れたように、CollectionType.Indexがランダムアクセス可能かどうかで使うアルゴリズムをを静的に切り替えるというようなことです。

単純化すると次のようになるでしょうか。

protocol P {
    typealias I
}

struct A<T>: P {
    typealias I = T
}

func f<T: P where T.I: IntegerType>(a: T) -> String {
    return "f for T.I: IntegerType"
}

func f<T: P where T.I == String>(a: T) -> String {
    return "f for T.I == String"
}

f(A<Int>()) // "f for T.I: IntegerType"
f(A<UInt8>()) // "f for T.I: IntegerType"
f(A<String>()) // "f for T.I == String"
// f(A<String?>()) // compile error

A<Int>A<String> で呼び出すf()を変えていますが、Aという具体的な型ではなくPという抽象型を介しているのが特徴です。実際には、オーバーロードによって挙動を変えるのではなく、まさにcountElements()の例のように、特定の条件を満たした時に効率のよいアルゴリズムを採用するという分岐に使うといいと思います。

ただしこの型引数の制約によるオーバーロードは、総称関数にしか使えません。総称型はそもそも型引数の違いによってオーバーロードできないからです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?