在 C++ 中,我可以这样做:
class foo {
template <class bar>
bar baz() {
return bar()
}
}
但是当我在 Swift 中尝试这个时:
class Foo {
func baz<Bar>() -> Bar {
return Bar()
}
}
我收到一个语法错误,表明 Swift 不支持显式泛型方法专门化。
Swift中有类似的实现吗?
最佳答案
我不知道C++中的代码到底是做什么的。但您可以使用 Type Constraints .
但是这对我来说仍然没有意义,因为在 Swift 中并不是每个类都有不带参数的构造函数。所以我想出了这段代码,但我不确定这是否有帮助:
protocol TypeWithEmptyConstructor {
init()
}
class SomeClass {
required init() {
}
}
extension SomeClass: TypeWithEmptyConstructor { }
class Foo {
func baz<Bar: TypeWithEmptyConstructor>() -> Bar {
return Bar()
}
}
关于c++ - 在 Swift 中定义显式泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25329382/