Gunnar
Gunnar

Reputation: 313

How to create a reference to arrays and boost::array (or ideas to not have to)?

I have

int valA[3] = {290, 340, 390};
int valB[3] = {160, 200, 240};

boost::array<myStruct, 4> myStructA = {{{250,8}, {170,8}, {70,8}, {30,3}}};
boost::array<myStruct, 4> myStructB = {{{50,4}, {110,6}, {220,6}, {270,8}}};

and I want to avoid copy and paste when doing the following:

if(useA) {
  // do a lot with valA and myStructA
}
else {
  // do a lot with valB and myStructB
}

So the idea is to have something like that (warning, non-working code inside):

if(useA) {
  int &val[3] = valA;
  boost::array &myStruct<myStruct, 4> = myStructA;
}
else {
  int &val[3] = valB;
  boost::array &myStruct<myStruct, 4> = myStructB;
}
// do a lot with val and myStruct

Is there any way to do so? Or is the general approach not good and there is a much cleaner solution?

I know of the rule "no arrays of references", but this should be a reference of an array... Or is it the same in the end?

Thanks for your help!

Upvotes: 0

Views: 481

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279285

int (&val)[3] = valA;

(You need the & to refer to val rather than int).

boost::array<myStruct, 4> &myStruct = myStructA;

(Template parameters are part of the type, not the variable name).

Also it needs to be int (&val)[3] = useA ? valA : valB; or equivalent, since in your example code you're planning to use val outside its scope.

Upvotes: 4

Konrad Rudolph
Konrad Rudolph

Reputation: 545628

That won’t work: after the ifs the references val and myStruct are no longer in scope.

You can use the conditional operator though:

int (&val)[3] = useA ? valA : valB;
boost::array<myStruct, 4>& myStruct = useA ? myStructA : myStructB;

Upvotes: 4

Logan Capaldo
Logan Capaldo

Reputation: 40336

For arrays, the syntax is

int (&val)[3] = valA;

For a UDT like boost::array it's simply

boost::array<myStruct, 4>& myStruct = myStructA;

Upvotes: 4

Related Questions