And*_*ndy 2 lambda c++11 std-function visual-studio-2013
我试图通过实现std::iterator我自己的双链表集合并尝试使用我自己的sort函数对它进行排序来更熟悉C++ 11标准.
我希望sort函数接受lamba作为一种排序的方式,通过使sort接受a std::function,但它不编译(我不知道如何实现move_iterator,因此返回集合的副本而不是修改传递的集合).
template <typename _Ty, typename _By>
LinkedList<_Ty> sort(const LinkedList<_Ty>& source, std::function<bool(_By, _By)> pred)
{
LinkedList<_Ty> tmp;
while (tmp.size() != source.size())
{
_Ty suitable;
for (auto& i : source) {
if (pred(suitable, i) == true) {
suitable = i;
}
}
tmp.push_back(suitable);
}
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
我对函数的定义是错误的吗?如果我尝试调用该函数,我会收到编译错误.
LinkedList<std::string> strings{
"one",
"two",
"long string",
"the longest of them all"
};
auto sortedByLength = sort(strings, [](const std::string& a, const std::string& b){
return a.length() < b.length();
});
Run Code Online (Sandbox Code Playgroud)
错误:没有函数模板"sort"匹配参数列表参数类型的实例是:(LinkedList,lambda [] bool(const std :: string&a,const std :: string&) - > bool)
附加信息,编译还给出以下错误:
错误 1错误C2784:'LinkedList <_Ty> sort(const LinkedList <_Ty>&,std :: function)':无法推断'
std::function<bool(_By,_By)>'的模板参数
更新:我知道排序算法是不正确的,并且不会做想要的事情,我无意将其保留原样,并且一旦声明正确就没有问题.
问题是像这样_By在里面使用std::function不能从lambda闭包中推断出来.你需要传入一个实际的std::function对象,而不是一个lambda.请记住,lambda表达式的类型是未命名的类类型(称为闭包类型),而不是 std::function.
你在做什么有点像这样:
template <class T>
void foo(std::unique_ptr<T> p);
foo(nullptr);
Run Code Online (Sandbox Code Playgroud)
在这里,也没有办法T从论证中推断出来.
标准库通常如何解决这个问题:它不以std::function任何方式限制自己,只是简单地将谓词的类型作为模板参数:
template <typename _Ty, typename _Pred>
LinkedList<_Ty> sort(const LinkedList<_Ty>& source, _Pred pred)
Run Code Online (Sandbox Code Playgroud)
这样,将推断闭合类型并且一切都很好.
请注意,您根本不需要 std::function - 只需要存储一个仿函数,或者通过运行时接口(而不是模板之类的编译时)传递它.
旁注:您的代码使用的是为编译器和标准库保留的标识符(标识符以下划线开头,后跟大写字母).这在C++中是不合法的,您应该在代码中避免使用这样的保留标识符.