泛型 – 快速通用函数中的位移
发布时间:2020-12-14 04:43:29 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个需要位移操作的通用函数.我得到了我不理解的行为.这是一个演示问题的简单函数. func testBytesT: IntegerType(bytesIn: [UInt8],inout dataOut: T){let outputSize = sizeof(T)var temp: T = 0dataOut = 0temp = bytesIn[0] as Ttemp = te
我正在尝试编写一个需要位移操作的通用函数.我得到了我不理解的行为.这是一个演示问题的简单函数.
func testBytes<T: IntegerType>(bytesIn: [UInt8],inout dataOut: T){ let outputSize = sizeof(T) var temp: T = 0 dataOut = 0 temp = bytesIn[0] as T temp = 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.为我之前在这里获得的总量做了修复! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读