C++ error C2893

2019-09-04 04:15发布

问题:

---Answered --> Make the operator functions const!

I am writing a template and keep getting the following error:

Error 1 error C2893: Failed to specialize function template 'unknown-type std::less::operator ()(_Ty1 &&,_Ty2 &&) const'

when trying to use the template with a class, even if the class has overloaded operators. Note that the template does work with primitives

    ____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);
}

回答1:

Declare operator < like

bool operator<(const CCustomer &RHS) const;

For example

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