在 C++ 中,如何让(嵌套的)比较仿函数引用封闭 class 的数据?
In C++, how to let a (nested) compare functor refer to data of the enclosing class?
我想为 std::set 设计一个自定义比较仿函数,它使用封闭 class(其中定义了集合)的缓存值。
我知道在 C++ 中,没有从嵌套 class 到封闭 class 的直接访问,您需要在嵌套 class 中存储一个指针(如SO 上的几个 questions/answers 已经很好地解释了)。
但我的问题是如何在比较函子中导入这样的指针(我的代码框架中的 pModel)?
我的代码框架:
using namespace std;
class Face;
class Model
{
public:
// ...
map<Face, double> areaCached;
double area(Face f)
{
if (areaCached.find(f) == areaCached.end())
{
double calculatedValue; // perform very expensive calculation
areaCached[f] = calculatedValue;
}
return areaCached[f];
}
struct CompareByArea
{
// how can I import the pModel pointer here?
bool operator() (const Face f1, const Face f2) const
{
return pModel->area(f1) < pModel->area(f2);
}
};
set<Face, CompareByArea> sortedFaces;
};
我给你一个带有引用的例子,只是因为我更喜欢它们而不是指针。
struct CompareByArea
{
CompareByArea(Model& aModel):model(aModel)
bool operator() (const Face& f1, const Face& f2) const
{
return model.area(f1) < model.area(f2);
}
Model& model;
};
并且您应该在 C++ 中优先引用指针。它更易于阅读和理解。
不同的关联容器将比较对象作为构造函数参数。也就是说,您将添加一个指向您的比较函数的指针,并添加一个设置此指针的构造函数。然后你构造你相应的设置:
class Model {
struct CompareByArea {
Model* model;
CompareByArea(Model* model): model(model) {}
bool operator()(Face const& f1, Face const& f2) const {
return model->area(f1) < model->area(f2);
}
};
std::set<Face, CompareByArea> sortedFaces;
// ...
public:
Model(): sortedFaces(CompareByArea(this)) {}
// ...
};
使用 this
可能会在 this
完全构造之前发出有关使用 this
的警告,但只要 this
未在 CompareByArea
的构造函数中使用访问 Model
没有问题。
我想为 std::set 设计一个自定义比较仿函数,它使用封闭 class(其中定义了集合)的缓存值。
我知道在 C++ 中,没有从嵌套 class 到封闭 class 的直接访问,您需要在嵌套 class 中存储一个指针(如SO 上的几个 questions/answers 已经很好地解释了)。
但我的问题是如何在比较函子中导入这样的指针(我的代码框架中的 pModel)?
我的代码框架:
using namespace std;
class Face;
class Model
{
public:
// ...
map<Face, double> areaCached;
double area(Face f)
{
if (areaCached.find(f) == areaCached.end())
{
double calculatedValue; // perform very expensive calculation
areaCached[f] = calculatedValue;
}
return areaCached[f];
}
struct CompareByArea
{
// how can I import the pModel pointer here?
bool operator() (const Face f1, const Face f2) const
{
return pModel->area(f1) < pModel->area(f2);
}
};
set<Face, CompareByArea> sortedFaces;
};
我给你一个带有引用的例子,只是因为我更喜欢它们而不是指针。
struct CompareByArea
{
CompareByArea(Model& aModel):model(aModel)
bool operator() (const Face& f1, const Face& f2) const
{
return model.area(f1) < model.area(f2);
}
Model& model;
};
并且您应该在 C++ 中优先引用指针。它更易于阅读和理解。
不同的关联容器将比较对象作为构造函数参数。也就是说,您将添加一个指向您的比较函数的指针,并添加一个设置此指针的构造函数。然后你构造你相应的设置:
class Model {
struct CompareByArea {
Model* model;
CompareByArea(Model* model): model(model) {}
bool operator()(Face const& f1, Face const& f2) const {
return model->area(f1) < model->area(f2);
}
};
std::set<Face, CompareByArea> sortedFaces;
// ...
public:
Model(): sortedFaces(CompareByArea(this)) {}
// ...
};
使用 this
可能会在 this
完全构造之前发出有关使用 this
的警告,但只要 this
未在 CompareByArea
的构造函数中使用访问 Model
没有问题。