Note that there are some explanatory texts on larger screens.

plurals
  1. POSome troubles with C++ template pointer-to-member based property realization
    primarykey
    data
    text
    <p>My target was to make properties in C++ like in C# - with non-trivial set/get behavior. Here, object of Property holds refs to master of the prop and its set/get methods.</p> <p>Realisation, content of Property.h:</p> <pre><code>#include &lt;iostream&gt; using namespace std; namespace First { template &lt;class Master, class Type&gt; struct Property { Master &amp;master; const Type (Master::*&amp;get) () const; Type (Master::*&amp;set)(Type value); Property ( Master &amp;master, const Type (Master::*get) () const, Type (Master::*set)(Type value) ): get(get), set(set), master(master) { } operator const Type() const { cout &lt;&lt; "inside" &lt;&lt; endl; return (master.*get)(); } Type operator = (Type value) { return (master.*set)(value); } }; // Test chamber. class R { float x; const float getx() const { cout &lt;&lt; "returning " &lt;&lt; 0 &lt;&lt; endl; return 0; } float setx(float value) { cout &lt;&lt; "setting " &lt;&lt; value &lt;&lt; " in place of " &lt;&lt; x &lt;&lt; endl; return x = value; } public: Property&lt;R, float&gt; X; R(): X(*this, &amp;R::getx, &amp;R::setx) { } }; } </code></pre> <p>I also created .cpp file:</p> <pre><code>#include "Property.h" using namespace First; int main() { R r; r.X = 10; float y = r.X; } </code></pre> <p>The program makes "assign" step, printing 'setting 0 to 10', but segfaults on call to "retrieve" step, no difference what code (or no at all) inside 'R::getx()'.</p> <pre><code>~/Sources$ ./a.out setting 10 in place of 0 inside zsh: segmentation fault ./a.out </code></pre> <p>It seems that call to (master.*get()) itself causes a failure. What is wrong in this code?</p> <p>UPD: A tested out that any other call to master's functions leads to segfault, only one call of (master.*set) successes. Seems that this call invalidates state of object, member-to-ptr, Property itself or Moon phase.</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.
 

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