当涉及std:function或lambda函数时,C+11不推断类型
template<class A>set<A> test(const set<A>& input) { return input;}
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;}
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 = filter(mySet,function<bool(int)>([](int i){return i%2==0;}));
std::function
?
编辑:
template<class A,class CompareFunction>set<A> filter(const set<A>& input,CompareFunction compare) { set<A> ret; for(auto it = input.begin(); it != input.end(); it++) { if(compare(*it)) { ret.insert(*it); } } return ret;}
set<int> result = filter(myIntSet,[](int i) { i % 2 == 0; });
template<class Value,class CompareType,class IndexType>auto filter(const set<Value>& input,CompareType compare,IndexType index) -> map<decltype(index(*(input.begin()))),Value> { map<decltype(index(*(input.begin()))),Value> ret; for(auto it = input.begin(); it != input.end(); it++) { if(compare(*it)) { ret[index(*it)] = *it; } } return ret;}
map<string,int> s = filter(myIntSet,[](int i) { return i%2==0; },[](int i) { return toString(i); });
慕姐8265434
芜湖不芜