使用模板时出现错误C2678

时间:2016-04-03 16:45:32

标签: c++ templates

我正在定义一个优先级队列并在自定义结构上使用它,但我收到此错误,我不知道如何解决它。

这是我的错误:

error C2678: binary '<' : no operator found which takes a left-hand operand 
of type 'const Location' (or there is no acceptable conversion)

我的结构位置

struct Location
{
   int x, y, value;
   Location(int a, int b);
   bool operator == (const Location& other);
   bool operator < (const Location& other);
};

Location:: Location(int a, int b) {
   x = a;
   y = b;
   value = 0;
}

bool Location:: operator == (const Location& other) {
    return (x == other.x && y == other.y);
}

bool Location:: operator < (const Location& other) {
    return value > other.value;
}

这是我的优先级队列

template<typename T>
struct my_priority_queue {

priority_queue<T, vector<T>, greater<T>> elements;
bool empty()
{
    return elements.empty();
}
void push(T item)
{
    elements.emplace(item);
}
T pop() 
{
    T best = elements.top();
    elements.pop();
    return best;
}
};

主要功能

int main() {
    Location a(0, 0);
    Location b(1, 2);
    Location c(3, 0);
    my_priority_queue<Location> my_pq;
    my_pq.push(a);
}

1 个答案:

答案 0 :(得分:1)

正如它所说的那样。

您的运营商无法在LHS上使用const Location,因为它不是const功能。

bool operator == (const Location& other) const;
bool operator <  (const Location& other) const;
//                                      ^^^^^^