在模板实例化中使用运行时值

use a run-time value in template instantiation

本文关键字:运行时 实例化      更新时间:2023-10-16

请考虑类A和函数对象A_lessA_less根据A::getvalue()的结果比较两个A指针。

class A {
    int getvalue(const string &Parameter);
};
struct A_less : public binary_function<A *, A *, bool> {
    A_less(const string &P) : Parameter(P) { }
    bool operator()(const A *lhs, const A *rhs) const {
        return A->getvalue(Parameter) < rhs->getvalue(Parameter);
    }
    string Parameter;
}

如何声明/创建A指针的排序容器(集合、优先级队列…),根据Parameter的特定(运行时)值按A_less排序?

像这样:

std::string p = ...;
std::set<A,A_less> m(A_less(p));

您必须指定模板参数Compare(这是set的第二个参数)。构造映射时,需要将比较函数对象赋予map的构造函数。