In the code below the offset global int is passed as a reference across the elements of a map consisting of int/A pairs. When initialized the global offset is passed in to each instance in A’s initialization. Works fine.
#include <map>
#include <string>
struct A
{
A( int& offset ) : offset { offset } {}
int& offset;
};
typedef std::map< const int, A > IntAMap;
typedef std::pair< const int, A > IntAMapPair;
struct H
{
H( std::initializer_list< IntAMapPair > initializerList ) : intAMap( initializerList ) {}
int offset2 { 0 };
IntAMap intAMap;
};
int main()
{
int offset = 0;
H h
{
{ 33, A { offset } },
{ 44, A { offset } }
};
for( auto elem : h.intAMap )
{
elem.second.offset += 5;
}
// offset == 10
return 0;
}
But in my real application, there are 4 variants map members (like, A, B, C, D) and each has its own set of referenced members. There will be many H’s as well (like H1, H2, H3,…). The A { list-of-referenced-variables… } could get to be long enough to disrupt the reading of the H declaration. Each variant would have its own ref list.
It is important to me for downstream H designers to have an easy overview of their H structure during declaration. As it is, to my way of thinking, the passed-in-by-reference variable – in this case, offset, distracts from that clear declaration overview and thus reduces maintainability of my production code. I don’t see why offset has to be exposed in the initialization when it is merely used as an H-internal A-specific construct.
My question is, is there a C++ way to define a type somewhere so that, in this case, A’s offset becomes a construct used internally across H’s map elements? See offset2 for where I should think the jointly used member could be placed. It would be okay to have a single typename used in A’s initialization, like
…{
{ 55, A { list-of-referenced-variables-for-A }},
{ 66, B { list-of-referenced-variables-for-B }…
}…
Aucun commentaire:
Enregistrer un commentaire