Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing struct members with array subscript operator
    text
    copied!<p>Let have a type T and a struct having ONLY uniform elements of T type.</p> <pre><code>struct Foo { T one, T two, T three }; </code></pre> <p>I'd like to access them in fallowing way:</p> <pre><code>struct Foo { T one, T two, T three T &amp;operator [] (int i) { return *(T*)((size_t)this + i * cpp_offsetof(Foo, two)); } }; </code></pre> <p>where <code>cpp_offsetof</code> macro (it is considered to be correct) is:</p> <pre><code>#define cpp_offsetof(s, m) (((size_t)&amp;reinterpret_cast&lt;const volatile char&amp;&gt;((((s*)(char*)8)-&gt;m))) - 8) </code></pre> <p>The C++ standard doesn't guarantee it, but can we assume that members are distanced by a fixed offset and above is correct, cross-platform solution?</p> <p><br> 100% compatible solution would be:</p> <pre><code>struct Foo { T one, T two, T three T &amp;operator [] (int i) { const size_t offsets[] = { cpp_offsetof(Foo, one), cpp_offsetof(Foo, two), cpp_offsetof(Foo, three) }; return *(T*)((size_t)this + offsets[i]); } }; </code></pre> <p><em>[edit]standard, compliant and faster version was presented by</em> <a href="https://stackoverflow.com/questions/3178347/accessing-struct-members-with-array-subscript-operator/3178461#3178461">snk_kid using pointers to data members</a><em>[/edit]</em><br> but it requires extra lookup table which I'm trying to avoid.</p> <p>//EDIT<br> And one more. I cannot use just an array and constants to index these fields, they have to be named fields of a struct (some macro requires that).</p> <p>//EDIT2<br> Why those have to be named fields of a struct? What is the macro? It is settings system of a bigger project. Simplifying it's sth like this:</p> <pre><code>struct Foo { int one; int two; } foo; struct Setting { void *obj, size_t filed_offset, const char *name, FieldType type } #define SETTING(CLASS, OBJ, FIELD, TYPE) { OBJ, cpp_offsetof(CLASS, FIELD), #OBJ #FIELD, TYPE } Setting settings[] = { SETTING(Foo, foo, one, INT_FIELD), SETTING(Foo, foo, two, INT_FIELD) }; </code></pre> <p>And once again: I'm not looking form 100% compatible solution but 99%. I'm asking if we can expect that some compilers will put non-uniform padding between uniform fields.</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