【问题标题】:How to pass std::less to a class template?如何将 std::less 传递给类模板?
【发布时间】:2020-09-24 22:55:21
【问题描述】:

我想传递一个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<:less> >::comp' 的未定义引用

我怎样才能做到这一点? (没有任何改变将std::less 作为参数传递给类的策略等)?

【问题讨论】:

  • can't reproduce,您使用的是哪个编译器?您在模板实例化中使用 &gt; &gt; 而不是 &gt;&gt; 的事实让我认为您使用的是 C++11 之前的编译器。因此,与任何其他 static 变量一样,您可能需要在类声明之外为 comp 添加存储定义,例如:std::less&lt;int&gt; MyClass&lt;std::less&lt;int&gt; &gt;::comp;
  • @RemyLebeau static 变量仅被声明,未定义。这不应该编译。
  • @Fureeish 我知道这一点,但它 does compile 对我来说没有单独的定义 comp
  • @RemyLebeau 它编译,但它doesn't link
  • 注意你可能不需要comp:godbolt.org/z/nPdbnP

标签: c++ templates comparator


【解决方案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&lt; 内:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2017-12-25
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多