为什么 stl Compare 函数不是成员?
只是好奇为什么 stl::sort 的比较函数不能是静态成员?
我有一个在标头中声明和定义的小辅助类 foo,但现在我必须创建一个 foo.cpp 文件来实现 cmp(),因此它不是多重定义的。
我还必须考虑一个适当的修饰名称,以便 fooCmp() 不会与任何其他 cmp() 冲突。
因为它无法访问任何成员变量,所以任何需要访问其他值(例如按距 foo.bar 的距离排序)的比较操作都需要复杂的 bind2nd 调用。
Just idly curious why the compare function for stl::sort can't be a static member?
I have a small little helper class foo that is declared and defined in a header, but now I have to create a foo.cpp file for the implementation of cmp() so it isn't multiply defined.
I also have to think of a suitably decorated name so fooCmp() doesn't clash with any other cmp().
Because it has no access to any member variables any compare operation that needs access to some other value (eg. sort by distance from foo.bar) needs the complex bind2nd call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定您在抱怨什么:
所以顺序可以是:
以下对我有用:
但是如果类有一些自然顺序那么为什么不只定义运算符< 为了班级。 这将允许您访问成员,并且对于大多数需要定义排序的标准容器/算法来说表现良好。
I am not sure what you are complaining about:
So order can be:
The following works for me:
But if the class has some natural ordering then why not just define the operator< for the class. This will allow you the access to the members and will behave nicely for most of the standard containers/algorithms that need to define an ordering.
如果您关心多重定义的比较函数,请尝试使用
静态
链接来声明该函数。 那么该函数的范围不会超出找到它的编译单元。也就是说,您的比较“函数”根本不需要是函数,而可以是函数对象。 函数对象非常类似于函数,但被实现为在常规类中采用适当参数的
operator()
。 由于它是一个常规类,因此您可以将构造函数参数传递给该类。这是一个简单的例子:
If you're concerned with a multiply defined compare function, try declaring the function with
static
linkage. Then the scope of the function does not extend past the compilation unit where it is found.That said, your compare "function" need not be a function at all, but can instead be a function object. A function object is very much like a function but is implemented as an
operator()
that takes the appropriate parameters within a regular class. Since it's a regular class, you can pass constructor parameters to the class.Here is a simple example:
实际上听起来这个功能是
在类中声明,
在标头中定义,但在类外部没有内联链接,
即:
而不是
第一个将导致该函数在每个编译单元中定义
actually sounds like the function was
declared in the class,
defined in the header but outside the class without inline linkage
ie something like:
instead of
the first of which will cause the function to be defined in every compilation unit that