Using a non-static class member inside a comparison function

左心房为你撑大大i 提交于 2019-12-06 16:02:47

Use a functor instead of a function:

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;
};

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));

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));

Make operators static as well, and you'll be able to use it in op_comp.

Alternatively, use a functor instead of a function:

class myCompareClass {
  public:
  bool operator() (
    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; 
  }
  private:
    ... operators ...
} myCompareObject;

std::sort(ops.begin(), ops.end(), myCompareObject) 

See more examples at cplusplus.com

If you want op_comp to be non-static you can use Boost.Lambda or Boost.Bind:

parser my_parser;
sort(ops.begin(), ops.end(), bind(&parser::op_comp, ref(my_parser)));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!