我有一个类似于下面的类。我正在使用boost库的配对堆,它需要比较器作为模板参数。我的比较器应该访问A类的数据和成员以进行比较。最初,我将"my_compare"声明为struct,并重载了()运算符。但是,除非将指向类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;
}
您需要在c
中存储一个A*
。也许是这样的:
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;
}
首先:my_compare
函数必须是一个独立函数,或生成static
。在你的情况下,真的没有办法绕过它。
但是,如果您确实需要访问A
类中的成员,那么您可以在c
结构中创建指向A
实例的指针:
struct c
{
A* a;
// Other members
};
然后在创建c
对象时,将a
指针设置为this
。
您应该使用一个函子。
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)
一样构造它。
注意,你必须让内部类成为朋友,这不是自动的。您可以声明它,使它成为朋友并定义它,也可以定义它,使其成为朋友,但您必须将运算符体放在类之外。