使用模板时选择正确的相等运算符
我试图编写一个 uint128_t 库(http://stackoverflow.com/questions/6119306/operator-overloading-c-placement)并且遇到了一个障碍:我需要对不同类型的整数进行操作,例如 uint128_t ^ uint64_t。我已经编写了运算符重载,例如 template
。我还需要能够执行uint128_t ^ uint128_t
。但是,由于我的 uint128_t 使用 2 个 uint64_t 来存储值,所以我不能简单地使用 uint128_t 作为 T。因此,我编写了 2 个不同的函数,一个以 T 作为参数类型,另一个以 uint128_t 作为类型。
问题是编译器对标准 c++ int 类型和 uint128_t 使用 T val
版本。我如何让编译器区分它们?
编辑:我在链接的类中有此代码:
template <typename T>
bool operator==(T val){
return (LOWER == (uint64_t) val);
}
bool operator==(uint128_t val){
return ((UPPER == val.upper()) && (LOWER == val.lower()));
}
如果我这样做,
uint128_t a(5), b(123, 45);
uint64_t c = 6;
(a == c);
(a == b);
两行都将使用顶部运算符。但是,由于 uint128_t 是 2 个部分,并且是一个对象,因此计算机会将 uint64_t 与类进行比较,而不是与值进行比较。如何强制计算机使用第二个 == 运算符?
im trying to write a uint128_t library (http://stackoverflow.com/questions/6119306/operator-overloading-c-placement) and ive hit a bump: i need to operate on different types of ints, such as uint128_t ^ uint64_t
. i have written the operator overloads such as template <typename t> uint128_t operator^(T val)
. i also need to be able to do uint128_t ^ uint128_t
. however, since my uint128_t uses 2 uint64_t s to store the values, i cant simply use uint128_t as T. thus, i have written 2 different functions, one with T as the argument type and the other with uint128_t as the type.
the problem is that the compiler is using the T val
version for both standard c++ int types and uint128_t. how do i get the compiler to differentiate between them?
edit: i have this code in the class in the link:
template <typename T>
bool operator==(T val){
return (LOWER == (uint64_t) val);
}
bool operator==(uint128_t val){
return ((UPPER == val.upper()) && (LOWER == val.lower()));
}
if i do
uint128_t a(5), b(123, 45);
uint64_t c = 6;
(a == c);
(a == b);
both lines would use the top operator. however, since uint128_t is 2 parts, and is an object, the computer will be comparing a uint64_t to a class, not to a value. how do i force the computer to use the second == operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了转换构造函数之外,您甚至不需要任何额外的重载。然后,您只需编写处理 uint128_t 的运算符,如果您尝试传递另一个可转换类型(例如 int),它将使用转换构造函数进行转换,然后将调用适当的运算符。
看,这有效:
http://ideone.com/BEq03
You shouldn't even need the extra overloads for anything other than the conversion constructors. Then you just write the operators that handle uint128_t, and if you try to pass another convertible type, such as an int, it will be converted using the conversion constructor, then the appropriate operator will be called.
See, this works:
http://ideone.com/BEq03
尝试将模板运算符从类中取出并使它们成为全局的,然后指定您需要的特定转换,即:
Try taking the template operators out of the class and making them global, then specifying the specific conversions you need, i.e: