使用
functor class
:
#include <map>
class Comp
{
public:
Comp(int x, int y) : x(x), y(y) {}
bool operator() (int a, int b) const { /* Comparison logic goes here */ }
private:
const int x, y;
};
int main()
{
std::map<int,float,Comp> m(Comp(value1,value2));
}
这类似于函数,但以运行时对象的形式。这意味着它可以有状态,包括运行时配置。你要做的就是超载
operator()
. 如果在类定义中定义了所有成员函数体(如上所述),那么编译器可能会内联所有内容,因此性能开销可以忽略不计。
如果你知道
value1
和
value2
编译时常数
template <int x, int y>
bool compare(int a, int b) { /* Comparison logic goes here */ }
int main()
{
std::map<int,float,compare<value1,value2> > m;
}