I'm trying to catch up on C++11 and all the great new features. I'm a bit stuck on lambdas.
Here's the code I was able to get to work:
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <functional>
using namespace std;
template<typename BaseT, typename Func>
vector<BaseT> findMatches(vector<BaseT> search, Func func)
{
vector<BaseT> tmp;
for(auto item : search)
{
if( func(item) )
{
tmp.push_back(item);
}
}
return tmp;
}
void Lambdas()
{
vector<int> testv = { 1, 2, 3, 4, 5, 6, 7 };
auto result = findMatches(testv, [] (const int &x) { return x % 2 == 0; });
for(auto i : result)
{
cout << i << endl;
}
}
int main(int argc, char* argv[])
{
Lambdas();
return EXIT_SUCCESS;
}
What I would like to have is this:
template<typename BaseT>
vector<BaseT> findMatches(vector<BaseT> search, function <bool (const BaseT &)> func)
{
vector<BaseT> tmp;
for(auto item : search)
{
if( func(item) )
{
tmp.push_back(item);
}
}
return tmp;
}
Basically I want to narrow down the possible lambdas to a sensible subset of functions. What am I missing? Is this even possible? I'm using GCC/G++ 4.6.
See Question&Answers more detail:os