【发布时间】:2011-10-31 06:49:46
【问题描述】:
我在 gcc 4.6.2 中使用 lambda 函数,并希望实现一个模板化的“map”函数,如下所示:
template<typename A, typename B> std::vector<B> map(const std::vector<A>& orig, const std::function<B(A)> f) {
std::vector<B> rv;
rv.resize(orig.size());
std::transform(begin(orig), end(orig), begin(rv), f);
return rv;
}
这不行,因为测试代码:
int main(int argc, char **argv) {
std::vector<int> list;
list.push_back(10);
list.push_back(20);
list.push_back(50);
std::vector<int> transformed = map(list, [](int x) -> int { return x + 1; });
std::for_each(begin(transformed), end(transformed), [](int x) { printf("-> %d\n", x); });
return 0;
}
给出这个错误:
test.cpp:49:80: error: no matching function for call to ‘map(std::vector<int>&, main(int, char**)::<lambda(int)>)’
test.cpp:49:80: note: candidate is:
test.cpp:6:49: note: template<class A, class B> std::vector<B> map(const std::vector<A>&, std::function<B(A)>)
如果我删除模板,直接使用向量,它编译得很好:
std::vector<int> map(const std::vector<int>& orig, const std::function<int(int)> f) {
std::vector<int> rv;
rv.resize(orig.size());
std::transform(begin(orig), end(orig), begin(rv), f);
return rv;
}
所以我定义模板的方式一定有问题。
以前有人遇到过这种情况吗?我知道 lambda 是非常新的。
【问题讨论】:
-
您知道在您帖子的示例中,您在调用
map_时定义了函数map?注意调用中的下划线... :-) -
抱歉打错了——我从一个文件中粘贴了十几个不同的尝试,看看我是否可以让编译器给我一个关于它不喜欢什么的更好的线索。我想我现在已经修好了。