简体   繁体   English

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

[英]use a run-time value in template instantiation

Please consider class A , and the function object A_less .请考虑类A和函数对象A_less A_less compares two A pointers, depending on the result of A::getvalue() . A_less比较两个A指针,具体取决于A::getvalue()的结果。

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;
}

How do I go about declaring/creating sorted containers (sets, priority_queues, ...), of A pointers, sorted by A_less depending on specific (run-time) values of Parameter ?我如何声明/创建A指针的排序容器(集合、priority_queues...),根据Parameter特定(运行时)值按A_less排序?

Like this:像这样:

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

You have to specify the template parameter Compare (which is 2nd for set ).您必须指定模板参数Compare (这是set第二个)。 When constructing a map, you need to give the comparison function object to the constructor of map .构造map时,需要将比较函数对象交给map的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM