我玩弄lambda函數在GCC 4.6.2,並且想實現這樣的模板「地圖」功能:如何將lambda(C++ 11)傳遞給模板化函數?
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'?請注意呼叫中的下劃線... :-) –
抱歉,錯別字 - 我從一個文件中粘貼了十幾次不同的嘗試,看我是否可以讓編譯器給我一個更好的線索,告訴它它做了什麼不喜歡。想想我現在已經修好了。 –