我在考虑根据this StackOverflow answer在
中在Swift中创建一个整数幂函数func **<T : IntegerType>(var base: T, var exponent: T) -> T {
var result: T = 1
assert(exponent >= 0, "Exponent cannot be negative")
while exponent > 0 {
if exponent & 1 != 0 {
result *= base
}
exponent = exponent >> 1
base *= base
}
return result
}
我认为我可以使用泛型来实现该函数,以便它适用于任何整数类型。
不幸的是,当我尝试使用exponent >> 1
时出现错误:
二元运算符&#39;&gt;&gt;&#39;不适用于两个T&#39;操作数
检查>>
的函数定义,我看到十个整数类型中的每一个都有一个,但没有定义其他类型。因此我很惊讶所有其他运算符都在工作,例如&
,但我注意到&
实际上被定义为适用于符合BitwiseOperationsType
的所有类型IntegerType
>>
似乎符合。
为<<
实施BitwiseOperationsType
和{{1}}运算符是否有原因?