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).
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
#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.
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á.
The compiler refers to swap
because std::sort
internally uses function swap. However as member function run
is declared as constant function
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With