问题
I'm trying to do some conditional work like so:
Type object;
if (cond) {
doSomeStuff();
object = getObject();
doMoreStuff();
} else {
doSomeOtherStuff();
object = getDifferentObject();
doEvenMoreStuff();
}
use(object);
The only way I can think of solving this is the duplicate the use
code (which is actually inline code in my application) and declare object
in each branch of the if
block. If I wanted to avoid duplicate code I'd have to wrap it in some use function, as I have above. In a real situation, this use
function will probably take 5+ parameters to essentially carry over the context. This all seems messy, and impossible to maintain.
if (cond) {
doSomeStuff();
Type object = getObject();
doMoreStuff();
use(object);
} else {
doSomeOtherStuff();
Type object = getDifferentObject();
doEvenMoreStuff();
use(object);
}
What's the best approach to tackling this? Type
has no default constructor, thus snippet 1 doesn't compile.
Some other languages support snippet 1 - Related question: Forcing uninitialised declaration of member with a default constructor
回答1:
You can use an IIILE (immediately invoked initializing lambda expression):
auto object = [&] {
if (cond) {
doSomeStuff();
auto object = getObject();
doMoreStuff();
return object;
} else {
doSomeOtherStuff();
auto object = getDifferentObject();
doEvenMoreStuff();
return object;
}
}(); // note that the lambda must be called
use(object);
This will work even if Type
is not default-constructible.
Here's a demo.
回答2:
Put it inside a function:
Type doStuffAndCreateType() {
doSomeStuff();
Type object = getObject();
doMoreStuff();
return object;
}
Type doOtherStuffAndCreateType() {
doSomeOtherStuff();
Type object = getObject();
doEvenMoreStuff();
return object;
}
Type object = cond ? doStuffAndCreateType() : doOtherStuffAndCreateType();
use( object );
回答3:
Have a look at std::optional
:
#include <optional>
std::optional<Type> object;
if (cond) {
doSomeStuff();
object = getObject();
doMoreStuff();
} else {
doSomeOtherStuff();
object = getDifferentObject();
doEvenMoreStuff();
}
use(object.value());
来源:https://stackoverflow.com/questions/62647060/how-can-i-conditionally-instantiate-an-object