我想把我写的小清单分类为研究。
以下是代码:
#include <list>
#include <algorithm>
template<typename T>
class MyList {
private:
std::list<T> myList;
bool sortFunc(const T &t1, const T &t2) {
return (t1 > t2);
}
public:
void add(T item) {
myList.push_back(item);
}
void mySort() {
myList.sort(sortFunc);
}
};
错误消息:
no matching function for call to 'std::list<int, std::allocator<int> >::sort(<unresolved overloaded function type>)'
我知道这应该是一个众所周知的错误,但我无法弄清楚问题是什么。
E D I T:
g ++编译器
错误讯息:
Info: Internal Builder is used for build
g++ -O3 -Wall -c -fmessage-length=0 -o "src\\firstone.o" "..\\src\\firstone.cpp"
In file included from ..\src\firstone.cpp:2:0:
..\src\mylist.h: In instantiation of 'void MyList<T>::mySort() [with T = int]':
..\src\firstone.cpp:25:17: required from here
..\src\mylist.h:34:3: error: no matching function for call to 'std::list<int, std::allocator<int> >::sort(<unresolved overloaded function type>)'
myList.sort(sortFunc);
^
..\src\mylist.h:34:3: note: candidates are:
In file included from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\list:64:0,
from ..\src\mylist.h:4,
from ..\src\firstone.cpp:2:
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\list.tcc:353:5: note: void std::list<_Tp, _Alloc>::sort() [with _Tp = int; _Alloc = std::allocator<int>]
list<_Tp, _Alloc>::
^
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\list.tcc:353:5: note: candidate expects 0 arguments, 1 provided
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\list.tcc:430:7: note: void std::list<_Tp, _Alloc>::sort(_StrictWeakOrdering) [with _StrictWeakOrdering = bool (MyList<int>::*)(const int&, const int&); _Tp = int; _Alloc = std::allocator<int>]
list<_Tp, _Alloc>::
^
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\list.tcc:430:7: note: no known conversion for argument 1 from '<unresolved overloaded function type>' to 'bool (MyList<int>::*)(const int&, const int&)'
答案 0 :(得分:4)
比较器不能直接用作非静态成员
你可以在课堂上创建static
,或者我建议在课堂外使用仿函数或函数
template <typename T>
bool sortFunc(const T &t1, const T &t2) {
return (t1 > t2);
}
然后,在你的课堂上使用
void mySort() {
myList.sort(sortFunc<T>);
}
答案 1 :(得分:1)
#include <functional>
...
void mySort()
{
myList.sort( std::bind( &MyList<T>::sortFunc, this, std::placeholders::_1, std::placeholders::_2 ) );
}
...
这适用于g ++,无需使方法成为静态。