1

Given a condition, I want to select with if-else a reference to some object.

How I am currently doing it:

A *tmpPtr;
if(testCondition)
    tmpPtr = &Manager.FirstObject;
else
    tmpPtr = &Manager.SecondObject;
A &objectRef = *tmpPtr;

Is there more straight forward way to do this, without using temporary pointer in C++14?

cigien
  • 57,834
  • 11
  • 73
  • 112
toothBe
  • 11
  • 1

1 Answers1

0

You could use the conditional (ternary) operator:

A& objectRef = testCondition ? Manager.FirstObject : Manager.SecondObject;

If you want to use the condition to create more than one reference at once (only testing testCondition one time), you could use std::tuple:

#include <tuple>

int main() {
    A FirstObject;
    A SecondObject;
    B ThirdObject;
    B FourthObject;

    auto refs = testCondition ? std::tuple<A&, B&>{FirstObject, ThirdObject} 
                              : std::tuple<A&, B&>{SecondObject, FourthObject};
    
    A& aref = std::get<0>(refs); // ref to FirstObject or SecondObject
    B& bref = std::get<1>(refs); // ref to ThirdObject or FourthObject
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108