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

How to pass std::less to a class template?

我想传递 std::less 但它作为模板传递给 class,像这样:

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 的初始化中我得到了错误:

undefined reference to `MyClass<std::less<int> >::comp'

我怎样才能完成这项工作? (不改变将 std::less 作为参数传递给 class 等的策略)?

与任何其他 static class 变量一样,您需要为每个要使用的特定模板实例提供 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