泛型 – 快速通用函数中的位移

泛型 – 快速通用函数中的位移,第1张

概述我正在尝试编写一个需要位移 *** 作的通用函数.我得到了我不理解的行为.这是一个演示问题的简单函数. func testBytes<T: IntegerType>(bytesIn: [UInt8], inout dataOut: T){let outputSize = sizeof(T)var temp: T = 0dataOut = 0temp = bytesIn[0] as Ttemp 我正在尝试编写一个需要位移 *** 作的通用函数.我得到了我不理解的行为.这是一个演示问题的简单函数.

func testBytes<T: IntegerType>(bytesIn: [UInt8],inout dataOut: T){let outputSize = sizeof(T)var temp: T = 0dataOut = 0temp = bytesIn[0] as Ttemp = temp << 1}

如果我这样做,那么最后一行在xcode中给出了一个错误“T不能转换为Int”.

我可以将最后一行更改为temp = temp<< (1为T) 然后此行的错误更改为“T不可转换为UInt8” 在这种情况下,这些错误消息中的任何一个都不会对我有意义.我可以做些什么来启用泛型类型的位移?

解决方法 我有一个更详细的 blog post on this topic,但基本上有三个步骤:

>使用bitshift运算符和UInt8中的构造函数创建一个新协议:

protocol BitshiftoperationsType {    func <<(lhs: Self,rhs: Self) -> Self    func >>(lhs: Self,rhs: Self) -> Self    init(_ val: UInt8)}

>声明与每个整数类型的扩展一致 – 很容易,因为它们已经在BitshiftoperationsType中实现了所有内容:

extension Int    : BitshiftoperationsType {}extension Int8   : BitshiftoperationsType {}extension Int16  : BitshiftoperationsType {}extension Int32  : BitshiftoperationsType {}extension Int64  : BitshiftoperationsType {}extension UInt   : BitshiftoperationsType {}extension UInt8  : BitshiftoperationsType {}extension UInt16 : BitshiftoperationsType {}extension UInt32 : BitshiftoperationsType {}extension UInt64 : BitshiftoperationsType {}

>添加通用约束,使T符合您的新协议:

func testBytes<T: IntegerType where T: BitshiftoperationsType>(bytesIn: [UInt8],inout dataOut: T){    let outputSize = sizeof(T)    var temp: T = 0    dataOut = 0    temp = T(bytesIn[0])    temp = temp << 1}

感谢Martin R.为我之前在这里获得的总量做了修复!

总结

以上是内存溢出为你收集整理的泛型 – 快速通用函数中的位移全部内容,希望文章能够帮你解决泛型 – 快速通用函数中的位移所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1007836.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存