Home > Enterprise >  what is the "written out" equivalent of a ternary assignment?
what is the "written out" equivalent of a ternary assignment?

Time:12-29

I have a struct that is non-default-constructibe.
I want to assign different values to an object of that struct depending on a condition. Since the struct is non-default-constructibe, it is not possible to declare an unitialized object of it. However, it is possible to do that with a ternary:

struct foo {
    foo(int a);
};

foo generateFoo1() {
    return foo(1);
}

foo generateFoo2() {
    return foo(2);
}

int main() {
    bool test = false;

    //compiles fine
    foo f = test ? generateFoo1() : generateFoo2();

    //the following does not compile
    foo f2;
    if(test) {
        f2 = generateFoo1();
    }else {
        f2 = generateFoo2();
    }
}

What would be a "written out" equivalent of the ternary assignment? I have simplicity in mind and the ternary is a thorn in my eye. I would like to keep it as clean/readable as possible.

CodePudding user response:

Adding a factory function can help you out here. Using

foo make_foo(bool test)
{
    if (test)
        return generateFoo1();
    else
        return generateFoo2();
}

lets you have code like

foo f = make_foo(test);
  • Related