Swift-模板参数
我想知道是否有一种方法可以执行相当于c ++
的模板,以定义某些整数上的通用类型基础。我知道Swift的通用类型,但我不想提供一种类型,而是INT。
在C ++中,看起来像:
template <int N>
class Vector {
int values[N];
}
Swift
中,我想使用它,就像
let vector = Vector<3>(1, 2, 4)
print(vector.sum())
Swift提供了一种基于类型但不是INT的模板的方法,这看起来很奇怪。我几乎可以使用generics和sizeof(t)
,通过int
,float
或double
,但是'D很棒。
I'm wondering if there is a way to do the equivalent of C++
's templating, to define a generic type base on some integer. I know of Swift's Generic Type, but I don't want to provide a Type but an Int.
In C++, it would look like :
template <int N>
class Vector {
int values[N];
}
And in Swift
, I'd like to use it like
let vector = Vector<3>(1, 2, 4)
print(vector.sum())
It seems weird that Swift provides a way to template based on Type but not on int. I could almost achieve it using generics and sizeof(T)
, passing Int
, Float
or Double
, but that'd be aweful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,Swift不支持这一点,因此我最终使用了一些协议来定义整数值。
类型检查非常有效(无法添加
vector&lt;三,int&gt;
,带有vector&lt;二,int int&gt;
),尽管写作有点重。我愿意接受建议!
It's unfortunate that Swift doesn't support this, so I ended up using some protocol to define an integer value.
Type checking works great (can't add
Vector<Three, Int>
withVector<Two, Int>
for example), though it's a bit heavy to write.I'm open to suggestions!