通用的<>用于C ++标准中的指针 [英] Universal less<> for pointers in C++ standard

查看:227
本文介绍了通用的<>用于C ++标准中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候我需要一组指针。每次发生时,我最终为一个指针类型写一个较少的<>实现 - 将两个指针转换为size_t并比较结果。

Many times I needed a set of pointers. Every time that happens, I end up writing a less<> implementation for a pointer type - cast two pointers to size_t and compare the results.

我的问题是 - 可用在标准?我找不到这样的东西。似乎很常见的情况...

My question is - is that available in the standard? I could not find anything like that. Seems like common enough case...

更新:似乎即将到来的标准修复了所有的更少的<>提供的指针类型和包括unordered_set的问题。

Update: it seems that the upcoming standard fixes all of the problems with less<> provided for pointer types and unordered_set included, too. In a few years this question will be moot.

同时,当前标准没有合法的解决方案,但是size_t cast工作。

In the mean time, the current standard has no "legal" solution to this, but size_t cast works.

更新更新:好吧,我会gobsmacked!不仅

Update for update: well, I'll be gobsmacked! Not only

std::map<void *, int, std::less<void*> > myMap;

有效,但即使

std::map<void *, int > myMap;

gcc 3.4.1。我一直在做所有这些演员什么,和litb是完全正确的。甚至他引用的部分编号在当前标准中是完全相同的。 Hurray!

And that's in gcc 3.4.1 . I've been doing all the these casts for nothing, and litb is perfectly right. Even the section number he cites is exactly the same in the current standard. Hurray!

推荐答案

两个指针可以与使用比较函数对象 less 更大等。否则,使用毯子运算符< 等,只有当指针指向元素的相同数组对象或一个过去的结束。否则,结果未指定。

Two pointers can be compared with using the comparison function objects less, greater etc. Otherwise, using blanket operator< etc, this is only possible if the pointers point to elements of the same array object or one past the end. Otherwise, results are unspecified.

20.3.3 / 8 在C ++ 03中


对于模板较大较小 greater_equal less_equal ,任何
指针类型的特殊化产生一个总订单,即使内置运算符< > < = > = 不要。

For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not.

不需要明确专门化并手动投射到 size_t :这将降低可移植性,即使,因为 reinterpret_cast 从指针到整数的映射是实现定义的,并且不需要产生任何顺序。

No need to explicitly specialize and manually casting to size_t: That would lower the portability even, since the mapping of reinterpret_cast from pointers to integers is implementation defined and is not required to yield any order.


编辑:有关更详细的答案,请参阅这一个

Edit: For a more detailed answer, see this one.

这篇关于通用的&lt;&gt;用于C ++标准中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆