Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I pass a lambda (c++11) into a templated function?
    primarykey
    data
    text
    <p>I'm playing around with lambda functions in gcc 4.6.2, and would like to implement a templated "map" function like this:</p> <pre><code>template&lt;typename A, typename B&gt; std::vector&lt;B&gt; map(const std::vector&lt;A&gt;&amp; orig, const std::function&lt;B(A)&gt; f) { std::vector&lt;B&gt; rv; rv.resize(orig.size()); std::transform(begin(orig), end(orig), begin(rv), f); return rv; } </code></pre> <p>This doesn't work, because the test code:</p> <pre><code>int main(int argc, char **argv) { std::vector&lt;int&gt; list; list.push_back(10); list.push_back(20); list.push_back(50); std::vector&lt;int&gt; transformed = map(list, [](int x) -&gt; int { return x + 1; }); std::for_each(begin(transformed), end(transformed), [](int x) { printf("-&gt; %d\n", x); }); return 0; } </code></pre> <p>gives this error:</p> <pre class="lang-none prettyprint-override"><code>test.cpp:49:80: error: no matching function for call to ‘map(std::vector&lt;int&gt;&amp;, main(int, char**)::&lt;lambda(int)&gt;)’ test.cpp:49:80: note: candidate is: test.cpp:6:49: note: template&lt;class A, class B&gt; std::vector&lt;B&gt; map(const std::vector&lt;A&gt;&amp;, std::function&lt;B(A)&gt;) </code></pre> <p>If I remove the templating, and use a vector directly, it compiles fine:</p> <pre><code>std::vector&lt;int&gt; map(const std::vector&lt;int&gt;&amp; orig, const std::function&lt;int(int)&gt; f) { std::vector&lt;int&gt; rv; rv.resize(orig.size()); std::transform(begin(orig), end(orig), begin(rv), f); return rv; } </code></pre> <p>so it must be a problem with the way I'm defining the template.</p> <p>Has anyone run into this before? I know lambdas are incredibly new.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload