当我定义这个功能时,
template<class A>
set<A> test(const set<A>& input) {
return input;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用test(mySet)代码中的其他地方调用它,而无需显式定义模板类型.但是,当我使用以下功能时:
template<class A>
set<A> filter(const set<A>& input,function<bool(A)> compare) {
set<A> ret;
for(auto it = input.begin(); it != input.end(); it++) {
if(compare(*it)) {
ret.insert(*it);
}
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
当我使用此函数调用时filter(mySet,[](int i) { return i%2==0; });
,出现以下错误:
错误:没有匹配函数来调用'filter(std :: set&,main()::)'
但是,所有这些版本都可以工作:
std::function<bool(int)> func = [](int i) { return i%2 ==0; };
set<int> myNewSet = filter(mySet,func);
set<int> myNewSet = filter<int>(mySet,[](int i) { return i%2==0; });
set<int> myNewSet …Run Code Online (Sandbox Code Playgroud)