Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading