我必须使用 STL 集并且我想定义我自己的比较函数。但根据我的要求,这个比较函数不应该是全局的,而应该是类的公共(public)成员。
//CLASS DEFINITION
class IDENTIFERS
{
public:
IDENTIFIERS();
~IDENTIFIERS();
bool compare_identifier(int Identifier, int Identifier);
public:
std::set <Identifier, bool(*)(Identifier, Identifier)> set_instance;
};
//CLASS Constructor
IDENTIFIERS::IDENTIFIERS()
{
std::set <Identifier, bool(*)(Identifier, Identifier)> set_instance(compare_identifier);
}
如果我像上面提到的那样写一段代码。它无法编译,因为比较函数的原型(prototype)与 compare_identifier() 函数不匹配。
有办法吗?
最佳答案
非静态成员函数为 this
采用隐式第一个参数,因此您的 compare_identifier
实际上有三个参数。如果你需要它是一个非静态成员函数,你需要将成员函数的隐式第一个参数绑定(bind)到一个IDENTIFIERS
的实例上,例如,
#include <set>
#include <functional>
struct Identifier { int id; };
class IDENTIFERS
{
public:
IDENTIFERS() : set_instance(std::bind(&IDENTIFERS::compare_identifier,
this,
std::placeholders::_1,
std::placeholders::_2))
{}
bool compare_identifier(const Identifier& lhs, const Identifier& rhs)
{
return lhs.id < rhs.id;
}
public:
std::set <Identifier, std::function<bool(const Identifier&, const Identifier&)>> set_instance;
};
关于c++ - C++ STL 集 : Can comparison function be a member function of a class? 的比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17250622/