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.为我之前在这里获得的总量做了修复!
总结以上是内存溢出为你收集整理的泛型 – 快速通用函数中的位移全部内容,希望文章能够帮你解决泛型 – 快速通用函数中的位移所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)