【问题标题】:C++ error C2893C++ 错误 C2893
【发布时间】:2015-02-24 22:37:55
【问题描述】:

---已回答 --> 使运算符函数为 const!

我正在编写模板并不断收到以下错误:

错误 1 ​​错误 C2893:无法专门化函数模板 'unknown-type std::less::operator ()(_Ty1 &&,_Ty2 &&) const'

尝试将模板与类一起使用时,即使该类具有重载运算符。请注意,模板确实适用于原语

    ____TEMPLATE_________

        #include <vector>
        #include <algorithm>
        using namespace std;


    template <class T>

    class Set{
        int elements;
        vector <T> MySet;

    public:

    //error is due to this function

    bool find(const T& value) const
        {
            return binary_search(MySet.begin(), MySet.end(), value);    
        }

_____CLASS_________



class CCustomer{
public:
    int CustomerId;
    string Name;
    string Surname;
    int Phone;

    CCustomer(int ID, string Name, string Surname, int Phone)
{
    this->CustomerId = ID;
    this->Name = Name;
    this->Surname = Surname;
    this->Phone = Phone;
}

    bool operator==(const CCustomer &RHS)
{
    if (this->CustomerId == RHS.CustomerId)
    {
        return true;
    }
    return false;
}
    bool operator<(const CCustomer &RHS)
{
    if (this->CustomerId < RHS.CustomerId)
    {
        return true;
    }
    return false;
}
    bool operator>(const CCustomer &RHS)
{
    if (this->CustomerId > RHS.CustomerId)
    {
        return true;
    }
    return false;
}

};

_____MAIN_______

void main()
{
    CCustomer TEST (1234, "abc", "def", 456);

    Set <CCustomer> Myset;
    Myset.find(Test);
}

【问题讨论】:

  • 让您的比较运算符成为const 成员。别再说if (b) return true else return false;,直接说return b;
  • bool operator&lt;(const CCustomer &amp;RHS) const { // ... 也用于其他比较运算符。此错误消息有什么不清楚的地方?
  • @juanchopanza 你完全正确!是的,我也这样退回了它们,这只是以前的构建,但感谢您的注意。非常感谢各位,加油! :)
  • 这不是“C++ 错误”,而是来自特定编译器的错误代码,我猜是微软的。如果您在他们的网站上搜索该错误代码,您也会找到解释。

标签: c++ algorithm templates search std


【解决方案1】:

声明运算符

bool operator<(const CCustomer &RHS) const;

例如

bool operator<( const CCustomer &RHS) const
{
    return this->CustomerId < RHS.CustomerId;
}

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 2017-08-01
    • 2014-04-28
    相关资源
    最近更新 更多