在比较函数内使用非静态类成员 [英] Using a non-static class member inside a comparison function

查看:134
本文介绍了在比较函数内使用非静态类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个语法分析器类,需要在代码的一点,以排序结构,保存操作符的信息。每个操作符都有一个优先级,这是用户通过我的分析器类的公共成员函数定义的。因此,当排序时,我需要我的排序功能,基于相应的运算符的优先级排序元素。我使用以下代码比较元素:

I'm currently developing a syntaxic analyser class that needs, at a point of the code, to sort structs holding info about operators. Each operator has a priority, which is user-defined through public member functions of my analyser class. Thus, when sorting, I need my sorting function to order elements based on the priority of the corresponding operator. I'm using the following code to compare elements:

bool parser::op_comp(const op_info& o1, const op_info& o2) {
    op_def& op1 = operators[o1.op_char];
    op_def& op2 = operators[o2.op_char];

    return op1.priority > op2.priority;
}



注意,我不得不使这个函数是静态的,因为它定义在类。

Note that I had to make this function static, since it's defined inside of a class.

事实上,我的比较函数比较类型 op_char 的元素,映射包含 op_def 类型的元素,其中有一个字段priority。

In fact, my compare function compares elements of type op_char, and I retrieve the operator def from a map which contain elements of type op_def, which have a field "priority".

是我不能管理使用 std :: sort(ops.begin(),ops.end(),std :: mem_fun_ref(& parser :: op_comp))(其中ops是向量的op_info)方法。我得到以下错误,这听起来很合乎逻辑:

The problem I'm facing is that I can't manage to use std::sort(ops.begin(), ops.end(), std::mem_fun_ref(&parser::op_comp)) (where ops is a vector of op_info) method. I get the following error, which sounds quite logical :

错误:在静态成员函数中无效使用成员`parser :: operators'

error: invalid use of member `parser::operators' in static member function

这里是我的问题:如何强制std ::排序使用comp函数,使用来自类的非静态成员的元素?显然,函数应该是非静态的,但如果我不使它静态,我不能使用它...

Here is my question : how can I force std::sort to use a comp function that makes use of elements from non-static members of the class ? Obviously the function should be non-static, but I can't manage to use it if I don't make it static...

先感谢您的帮助,
CFP。

Thanks in advance for your help, CFP.

推荐答案

使用函数代替函数:

struct op_comp : std::binary_function<op_info, op_info, bool>
    {
    op_comp(parser * p) : _parser(p) {}
    bool operator() (const op_info& o1, const op_info& o2) {
        return _parser->op_comp(o1, o2);
    }
    parser * _parser;
};

这样,方法 op_comp -静态的。然而,调用者需要一个解析器的实例,所有的操作符都存储在其中。这是我们的新函数的用法:

This way the method op_comp can stay non-static. However the caller needs an instance of the parser, where are all the operators are stored. This is the usage of our new functor:

std::sort(ops.begin(), ops.end(), op_comp(&my_parser));

其中 my_parser 是解析器的实例you正在使用。或者,如果您从解析器调用 std :: sort ,您可以简单地写:

Where my_parser is the instance of parser you are using. Alternatively, if you are calling std::sort from the parser, you can simply write:

std::sort(ops.begin(), ops.end(), op_comp(this));

这篇关于在比较函数内使用非静态类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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