Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing std::function with union in C++11
    text
    copied!<p>I am trying to define a class that has functions with different numbers of parameters stored in a union. The class is initialized with a function object and necessary parameters. I am getting these compiler errors at the locations marked (1) and (2)</p> <p>(1) Destructor of '_' is implicitly deleted because variant field 'f_V' has a non-trivial destructor</p> <p>(2) Destructor of 'MyClass' is implicitly deleted because field 'functions' has a deleted destructor</p> <p>I simply want to declare a union of different function objects, and depending on the parameters passed-in be able to pick the appropriate function and call it. Why am I getting these errors and how should I rewrite this code?</p> <pre><code>template&lt;typename VARIABLE&gt; struct MyClass { MyClass(VARIABLE *p, const std::function&lt;void (VARIABLE&amp;)&gt;&amp; f) { functions.f_V = f; ... } protected: union _ { std::function&lt;void (VARIABLE &amp;)&gt; f_V; // (1) std::function&lt;void (const VARIABLE &amp;, VARIABLE &amp;)&gt; f_vV; std::function&lt;void (const VARIABLE &amp;, const VARIABLE &amp;, VARIABLE &amp;)&gt; f_vvV; std::function&lt;void (const VARIABLE &amp;, const VARIABLE &amp;, const VARIABLE &amp;, VARIABLE &amp;)&gt; f_vvvV; } functions; // (2) ... }; </code></pre> <p>EDIT: I am trying to accomplish storage of lambda functions having variable argument lists in a container. Something like this:</p> <pre><code>std::vector&lt;MyClass&lt;MyVariable&gt;&gt; myContainerOfLambdas; MyVariable A,B,TO; auto lambda1 = [this](const MyVariable&amp; a, MyVariable&amp; to) { ... }; myContainerOfLambdas.push_back(MyClass&lt;MyVariable&gt;(A,TO,lambda1)); auto lambda2 = [this](const MyVariable&amp; a, const MyVariable&amp; b, MyVariable&amp; to) { ... }; myContainerOfLambdas.push_back(MyClass&lt;MyVariable&gt;(A,B,TO,lambda2)); ... // iterate over the stored MyClass objects holding the lamda functions and the parameters // to call them for(MyClass&lt;MyVariable&gt; &amp; e:myContainerOfLambdas) { e(); // here the appropriate lambda function will be invoked with the appropriate values // stored in MyClass } </code></pre> <p>NOTE: For brevity I have omitted the definition of the () operator in MyClass, but it simply calls the right function object with the right parameters.</p> <p>If you see a better design approach to this, fine, please direct me in the right direction. Thanks!</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