Home > Software engineering >  Changing const references
Changing const references

Time:11-04

Suppose I have a function that returns a const reference. I cannot change this function. Also I have another class called MyClass

const Value& GetValue(const MyClass& m, const unsigned long i) {
    ....
    val is assigned by using m & i
    ...
    return val;
}

Somewhere else in the code. I have to implement another function:

void NewFunction(int r, int i)
{
    MyClass a = GetClass();
    MyClass b = GetClass();
    MyClass c = GetClass();

    ...
    Above a, b, and c are modified differently
    ....

    const Value& cv;
    if (r==1)
        cv = GetValue(a,i);
    else if (r==2)
        cv = GetValue(b,i);
    else
        cv = GetValue(c,i);

    ...
}

First "const Value& cv;" needs to be assigned at declaration but i don't know what the assignment will be at declaration until i go through the conditional if-else. Second "GetValue" returns a const so I don't know how to handle that and if i can safely change "cv" later

I cannot change the templates of the functions.

Do I have to resort to pointers or is there another elegant way to handle this?

Edit: To add to the complexity, Value is an abstract class so I can't do

Value cv;

because the compiler rightly complains "object of abstract class is not allowed"

CodePudding user response:

Although it's not the prettiest, you could use nested ternaries:

const Value& cv = (a == 1) ? GetValue(a, i)
    : (a == 2) ? GetValue(b, i)
    : GetValue(c, i)

You could also do something like:

MyClass obj_to_pass;
if (a==1)
    obj_to_pass = a;
else if (a==2)
    obj_to_pass = b;
else
    obj_to_pass = c;


const Value& cv = GetValue(obj_to_pass, i);

CodePudding user response:

const Value& NewFunctionHelper(int a, const unsigned long i, const MyClass& a, const MyClass& b, const MyClass& c) {
    if (a==1)
        return GetValue(a,i);
    else if (a==2)
        return GetValue(b,i);
    else
        return GetValue(c,i);
}

And then in your normal method:

Above a, b, and c are modified differently
....
const Value& cv = NewFunctionHelper(a, i, a, b, c);
  • Related