sort() - 没有用于调用'swap'的匹配函数

时间:2020-12-16 09:43:53

Just spent about an hour trying to figure out why I would get 20 error messages of the type "Semantic issue - no matching function for call to 'swap'" when I try to build the following class (in XCode).

花了大约一个小时试图找出为什么我会在我尝试构建以下类(在XCode中)时得到20个类型为“语义问题 - 没有用于调用'swap'的匹配函数”的错误消息。

test.h

test.h

#include <iostream>
#include <string>
#include <vector>


class Test{
    std::vector<std::string> list;

    void run() const;
    static bool algo(const std::string &str1, const std::string &str2);
};

test.cpp

TEST.CPP

#include "test.h"


void Test::run() const {
    std::sort( list.begin(), list.end(), algo );
}


bool Test::algo(const std::string &str1, const std::string &str2){
    // Compare and return bool
}

Most of the people with the same problem seem to have made their algorithm a class member instead of a static member, but that is clearly not the problem here.

大多数具有相同问题的人似乎已经使他们的算法成为类成员而不是静态成员,但这显然不是问题。

2 个解决方案

#1


16  

It turns out it's a very simple problem, but not very obvious to spot (and the error message doesn't do a very good job in helping out either):

事实证明这是一个非常简单的问题,但发现并不是很明显(并且错误消息在帮助中也没有做得很好):

Remove the const declaration on run() - voilá.

删除run()上的const声明 - voilá。

#2


6  

The compiler refers to swap because std::sort internally uses function swap. However as member function run is declared as constant function

编译器引用swap,因为std :: sort内部使用函数交换。但是,当成员函数run被声明为常量函数时

void run() const;

then the object of the class itself is considered as a constant object and hence data member list also is a constant object

那么类本身的对象被认为是一个常量对象,因此数据成员列表也是一个常量对象

std::vector<std::string> list;

So the compiler tries to call swap with parameters that are constant references or even are not references and can not find such a function.

因此,编译器尝试使用常量引用的参数调用swap,甚至不是引用,也无法找到这样的函数。

#1


16  

It turns out it's a very simple problem, but not very obvious to spot (and the error message doesn't do a very good job in helping out either):

事实证明这是一个非常简单的问题,但发现并不是很明显(并且错误消息在帮助中也没有做得很好):

Remove the const declaration on run() - voilá.

删除run()上的const声明 - voilá。

#2


6  

The compiler refers to swap because std::sort internally uses function swap. However as member function run is declared as constant function

编译器引用swap,因为std :: sort内部使用函数交换。但是,当成员函数run被声明为常量函数时

void run() const;

then the object of the class itself is considered as a constant object and hence data member list also is a constant object

那么类本身的对象被认为是一个常量对象,因此数据成员列表也是一个常量对象

std::vector<std::string> list;

So the compiler tries to call swap with parameters that are constant references or even are not references and can not find such a function.

因此,编译器尝试使用常量引用的参数调用swap,甚至不是引用,也无法找到这样的函数。