Note that there are some explanatory texts on larger screens.

plurals
  1. POAnonymous function C++
    text
    copied!<p>I am trying to use the function <code>signal(int,void(*)(int))</code> from <code>&lt;csignal&gt;</code> to handle the floating point exception SIGFPE. I'd like to be able to print some useful diagnostics besides just a message saying "Floating point exception" or something to that effect. This means the function I pass as the handler to <code>signal</code> needs access to some of the data in my code. Therein lies the rub.</p> <p>The function must return <code>void</code> and accept only 1 parameter of type <code>int</code>. I cannot make the handler a member function of my data storage class since then the type would be <code>void(Foo::*)(int)</code> due to the hidden <code>this</code> pointer.</p> <p>I thought about using lambdas to try and make an anonymous function like this;</p> <pre><code>void handler(int nSig, Foo data) { // do something } // snip Foo data; signal(SIGFPE, [&amp;](int nSig)-&gt;void{handler(nSig,data);}); </code></pre> <p>however because the lambda captures the variable <code>data</code> from outside the compiler will not let it be cast to a pointer to <code>void(*)(int)</code> (which is a shame as this seems like an ideal use for lambdas).</p> <p>I could simply make <code>data</code> a global variable which could then be seen in <code>handler</code> but I am loath to do this for obvious reasons.</p> <p>So my question is thus; <strong>what is the best way of mimicking anonymous functions in C++</strong>?</p> <p>Note: I would prefer a native C++ solution and not to have to use boost or equivalent.</p>
 

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