我试图赶上C++ 11和所有伟大的新功能。我有点卡在lambdas上。Lambdas和std :: function
这是我能得到工作代码:
#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;
}
我想有是这样的:
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;
}
基本上我想可能lambda表达式缩小到一个合理的功能的子集。 我错过了什么?这甚至有可能吗?我正在使用GCC/G ++ 4.6。
如果你想做什么(即使用'std :: function'),你会得到什么错误?也不是说GCC没有完全支持一些C++ 11的支持,即使在GCC 4.7中也不支持4.6。 – 2012-08-02 09:07:54
你的第二个代码示例看起来不错;你会得到什么错误? – ecatmur 2012-08-02 09:10:54
模板只允许精确匹配,因此您无法将lambda函数传递给期望使用'std :: function'的函数模板。而且,'function'构造函数不需要拒绝那些实际上不匹配'function'签名的参数,所以实际上并没有用于缩小范围。 – JohannesD 2012-08-02 09:15:25