【发布时间】:2022-01-11 17:56:56
【问题描述】:
假设我想根据依赖于条件的复杂计算分配一个 const 变量。
如果情况很简单,我可以这样做:
const int N = myBool ? 1 : 2;
但它更像
const int N = myBool ? <lengthy calculation> : <other lengthy calculation>;
我正在做的是这个,但我想要更干净的东西:
int N_nonconst;
if (myBool) {
N_nonconst = <lengthy calculation>;
}
else {
N_nonconst = <other lengthy calculation>;
}
const int N = N_nonconst;
显然,我也可以这样做:
int possibility1 = <lengthy calculation>;
int possibility2 = <other lengthy calculation>;
const in N = myBool ? possibility1 : possibility2;
但我实际上只想执行其中一项冗长的计算。
如果我要扩展语言,我会考虑做出类似const_deferredAssignment 的声明:
const_deferredAssignment int N;
if (myBool) {
N = <...>;
}
else {
N = <...>;
}
我也可以将这些计算封装在函数/方法中,但它们使用了一堆局部变量,所以这将是一个相当冗长的函数调用。
【问题讨论】:
-
“相当冗长的函数调用”会有什么问题?
-
没什么技术性,只是比我希望的更冗长。
-
顺便说一句,Swift 允许您声明一个由 if/else 块立即设置的未初始化的 const var。我希望 C++ 做到这一点。
标签: c++ conditional-statements constants variable-assignment