假设我想基于依赖于条件的复杂计算来分配常量变量。
如果情况简单,我可以做:
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 = <...>;
}
我也可以将这些计算封装在函数/方法中,但它们使用了一堆本地函数,所以这将是一个相当冗长的函数调用。
您可以将每个计算封装在lambda中,并捕获局部变量以减少其参数的冗长性
{
// ...
auto firstFunc = [&]() -> int { ... };
auto secondFunc = [&]() -> int { ... };
const int N = myBool ? firstFunc() : secondFunc();
}
通过这种方式,实际上只执行两个功能中的一个。
您可以将冗长的计算转移到一个单独的函数:
int lengthCalculation()
{
if(myBool)
{
return <lengthy calculation>;
}
else
{
return <other lengthy calculation>;
}
}
const int N = lengthCalculation();
如果你不想创建一个单独的函数,你可以使用本地lambda:
const int N = [&]()
{
if(myBool)
{
return <lengthy calculation>;
}
else
{
return <other lengthy calculation>;
}
}();
您可以尝试使用
SWITCH(myBool)
{
Case 0 : first_lengthy_calculation
Break;
Case 1 : second_lengthy_calculation
Break;
}