问题描述
我正在尝试像这样做一些有条件的工作:
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);
我认为解决此问题的唯一方法是重复使用 代码(实际上是我的应用程序中的内联代码),并在
if
块的每个分支中声明 object
。如果我想避免重复的代码,则必须像上面一样将其包装在一些use函数中。在实际情况下,此 use
函数可能会使用5个以上的参数来实质上继承上下文。
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);
}
解决此问题的最佳方法是什么? Type
没有默认构造函数,因此代码段1无法编译。
What's the best approach to tackling this? Type
has no default constructor, thus snippet 1 doesn't compile.
某些其他语言支持代码段1-相关问题:
Some other languages support snippet 1 - Related question: Forcing uninitialised declaration of member with a default constructor
推荐答案
您可以使用IIILE(立即调用初始化lambda表达式):
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);
即使 Type
不是默认可构造的,这也将起作用。
This will work even if Type
is not default-constructible.
这是一个。
这篇关于如何有条件地实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!