Note that there are some explanatory texts on larger screens.

plurals
  1. POPointers to members of members or an alternative?
    primarykey
    data
    text
    <p>Say I have a template function which sets data in a struct via pointers-to-member:</p> <pre><code>struct S { double d; unsigned int u; }; struct A { S s, s2; float f; int i; }; template&lt;typename Stream, typename Class, typename Type&gt; void read(Stream&amp; s, Class&amp; out, Type Class::*member) { s &gt;&gt; out.*member; } </code></pre> <p>Now for regular members like <code>f</code> and <code>a</code> I can use this function on an arbitrary instance of <code>struct A</code>:</p> <pre><code>#include &lt;sstream&gt; int main(int, char**) { std::stringstream stream; A a; stream.clear(); stream.str("1"); read(stream, a, &amp;A::i); stream.clear(); stream.str("1.5"); read(stream, a, &amp;A::f); stream.clear(); stream.str("2"); printf("%i\n", a.i); printf("%f\n", a.f); } </code></pre> <p>But is there any way to access members of <code>A::s</code> or <code>A::s2</code> in a similar fashion <em>without</em> writing a new, effectively identical function for every composite member (<code>s</code>, <code>s2</code>, etc.)? Pointers to members of members do not exist to my knowledge, but is there an alternative solution? (It has to work on arbitrary instances of a <code>struct</code> or <code>class</code>, similarly to how the pointer-to-member solution above works and should not require additional methods in <code>A</code> or <code>S</code>).</p> <p>To clarify the question somewhat (see also the comments in <a href="https://stackoverflow.com/a/16928366/2361316">this answer</a>): In the real code (a config file reader), the caller does a lookup in a map with a first string and doesn't actually know what is currently being read (using the second string), as the pointer-to-member parameter is bound. Also the map is initialized once and used for multiple instances of <code>A</code>, therefore the pointers-to-members.</p> <p>Please note the c++03 tag. Therefore c++11 lambdas are not an option.</p>
    singulars
    1. This table or related slice is empty.
    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