Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing an arbitrary lambda expression to a function?
    primarykey
    data
    text
    <p>I have a pretty exotic problem, since I am trying to create some sort of a compiler... I want to pass a lambda expression to a templated function like this:</p> <pre><code> template&lt;class T&gt; delegate&lt;T&gt;* bind(std::function&lt;T&gt; func) { return nullptr; } </code></pre> <p>So that I can now call</p> <pre><code>bind([&amp;](int a) { // do something }); </code></pre> <p>... So normally, this wouldn't be a problem, since std::function is able to capture a lambda. But here the problem is that (let's assume) I don't know or don't want to provide the info about what "T" is exactly. It could be any function signature you could also insert into std::function&lt;>...</p> <p>I also need to pass this "inferred" signature back to the "delegate" class I want to return and that delegate class needs to be a pointer to class...</p> <p>For now I have come up with this:</p> <pre><code>template&lt;class T&gt; struct delegate : public std::function&lt;T&gt; { delegate(const std::function&lt;T&gt;&amp; func) : std::function&lt;T&gt;(func) { } delegate(const delegate&lt;T&gt;&amp; func) { } }; template&lt;class T&gt; delegate&lt;T&gt;* bind(std::function&lt;T&gt;&amp;&amp; func) { return new delegate&lt;T&gt;(std::forward&lt;std::function&lt;T&gt;&gt;(func)); } </code></pre> <p>But the above example of a call to "bind" fails with "failed template argument deduction". How can I get this to work without having to specify the "T" parameter explicitly when calling "bind" (then it works, at least)?</p> <p>Since in theory my compiler has all the info to workaround this issue, I could just insert the instance of "T", but this would make the generated code unnecessarily convoluted.</p> <p>BTW, I am using the lastest Clang compiler.</p> <hr> <p>Here is the final solution:</p> <pre><code> template&lt;typename T&gt; struct get_signature; template&lt;typename Mem, typename Ret, typename... Args&gt; struct get_signature&lt;Ret(Mem::*)(Args...) const&gt; { typedef Ret type(Args...); }; template&lt;class T&gt; delegate&lt;typename get_signature&lt;decltype(&amp;T::operator())&gt;::type&gt;* bind(T func) { return nullptr; } </code></pre> <p>Be aware that you may need to adjust the "const" modifiers to your needs.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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