c++ - 在 Swift 中定义显式泛型方法

标签 c++ templates generics swift

在 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/

相关文章:

c++ - C++:为什么掷骰子偶数时我的骰子掷骰函数只返回偶数整数?

C++:泛型类中的非泛型方法?

java - 从通用树到领域特定树

c++ - 在堆栈与堆中没有构造函数的结构/类的初始化

c++ - 使用折叠表达式合并多个 vector

c++ - Windows SearchPath 函数

c++ - invoke_result_t<> 没有将 lambda 与引用参数匹配

c++ - 模板参数简化

java - 针对 XML 架构(XSD 文件)的通用 XML 文件 validator

基于对象类型的 Java getter 返回类型