如何将std :: less传递给类模板?

时间:2020-09-24 22:55:21

标签: c++ templates comparator

我想传递std::less,但将其作为模板传递给类,如下所示:

template<typename Comparator>
class MyClass{
    static Comparator comp;//Looks like this class in not multithread-safe :p
public:
    int value;
    bool operator<(const MyClass& other){return comp(this->value, other.value);}
};

int main()
{
    cout << boolalpha;
    MyClass<std::less<int> > mc1{3};
    MyClass<std::less<int> > mc2{5};

    cout << (mc1 < mc2) << endl;
    return 0;
}

但是在mc1mc2的初始化中,我得到了错误:

对`MyClass > :: comp'的未定义引用

我该如何进行这项工作? (将std::less作为参数传递给类的策略没有改变,等等)?

1 个答案:

答案 0 :(得分:1)

与其他任何static类变量一样,您需要为要使用的每个特定模板实例化提供comp的存储定义,例如:

template<typename Comparator>
class MyClass{
    static Comparator comp;//Looks like this class in not multithread-safe :p
public:
    int value;
    bool operator<(const MyClass& other){return comp(this->value, other.value);}
};

template<>
std::less<int> MyClass<std::less<int> >::comp; // <-- add this

int main()
{
    cout << boolalpha;
    MyClass<std::less<int> > mc1{3};
    MyClass<std::less<int> > mc2{5};

    cout << (mc1 < mc2) << endl;
    return 0;
}

但是,even this无法解决“未解决的”链接器错误。

在现代C ++中,您可以改为内联初始化comp

template<typename Comparator>
class MyClass {
    static constexpr auto comp = Comparator{};
public:
    int value;
    bool operator<(const MyClass& other) {
        return comp(this->value, other.value);
    }
};

Live Demo

否则,您可以将comp的声明移到operator<内:

template<typename Comparator>
class MyClass{
public:
    int value;
    bool operator<(const MyClass& other){
        static Comparator comp;
        return comp(this->value, other.value);
    }
};

Live Demo

或者,完全摆脱comp

template<typename Comparator>
class MyClass{
public:
    int value;
    bool operator<(const MyClass& other){
        return Comparator()(this->value, other.value);
    }
};

Live Demo