1

我有一个类似于以下的课程。我正在使用需要比较器作为模板参数的 boost 库的配对堆。我的比较器应该访问 A 类的数据和成员以进行比较。最初,我将 'my_compare' 声明为结构并重载 () 运算符。但是除非将指向 A 类的指针('this')传递给它,否则该结构无法访问 A 类的数据。但这意味着 my_compare 不再是编译时常量,并且会产生错误:“this”不能出现在常量表达式中。

作为第二次尝试,我将 my_compare 声明为成员函数(以便它可以访问成员和数据)。我现在收到以下错误:

error: type/value mismatch at argument 1 in template parameter list for 
‘template<class T> struct boost::heap::compare’

我怀疑有两种可能的解释:“my_compare”不是(函数)对象,也不是二进制函数,因为“this”是隐式传递的。我该如何解决这个问题。

class A{
public:
  //some data(properties)
  struct c{
    //some data  
  };
  double method1(int variable);
  double method2(const struct c&);

  bool my_compare(struct c& c, struct c& d){
     //accesses member methods and data    
  }

  typedef boost::heap::pairing_heap<struct c, boost::heap::compare<my_compare> > myheap;

}
4

3 回答 3

2

首先要做的事情是:该功能my_compare必须是独立的功能,制成。在你的情况下真的没有办法解决。static

但是,如果您确实需要访问A类中的成员,则可以在c结构中创建指向A实例的指针:

struct c
{
    A* a;
    // Other members
};

然后,当您创建一个c对象时,您将a指针设置为this.

于 2013-08-07T09:07:52.167 回答
2

你需要存储一个A*inside c。或许是这样的:

class A{
public:
  //some data(properties)
  struct c{
    //some data  
    A* owner_A;
    c(A* a) : owner_A(a) {}
  };
  double method1(int variable);
  double method2(const struct c&);

  static bool my_compare(struct c& c, struct c& d){
     //accesses member methods and data  
     c->owner_A->method1(42);  
     d->owner_A->method2(d); 
  }

  typedef boost::heap::pairing_heap<struct c, boost::heap::compare<my_compare> > myheap;

}
于 2013-08-07T09:09:47.937 回答
2

比你应该使用仿函数。

class A {
    struct my_compare;
    friend struct my_compare;
    struct my_compare {
        A &self;
        A(A &self) : self(self) {}
        bool operator()(struct c& c, struct c& d) {
            // access member data and methods on self
        }
    };
}

当然你必须告诉它使用哪个 A实例,所以你必须像my_compare(*this)构造堆时那样构造它。

请注意,您必须使内部类成为朋友,这不是自动的。您可以声明它,使其成为朋友并定义它,或者您可以定义它,使其成为朋友,但您必须将运算符主体放在类之外。

于 2013-08-07T09:17:01.427 回答