【问题标题】:use a run-time value in template instantiation在模板实例化中使用运行时值
【发布时间】:2014-04-14 13:42:20
【问题描述】:

请考虑类A,以及函数对象A_lessA_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;
}

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

【问题讨论】:

    标签: c++ templates stl containers sorted


    【解决方案1】:

    像这样:

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

    您必须指定模板参数Compareset 的第二个参数)。构造地图时,需要将比较函数对象交给map的构造函数。

    【讨论】:

    • 很好,现在我知道set(Compare &amp;comp) ctor 需要什么。用 gcc 很好地编译,MS 编译器有一些警告 C4930: 'std::set<_kty> T(A_less)': 未调用原型函数(是否打算定义变量?)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2022-11-21
    • 2011-06-03
    相关资源
    最近更新 更多