是否有一种方法可以编写此短片而不捕获lambda变量

Is there a way of writing this shorter without capturing lambda variables?

本文关键字:短片 变量 lambda 方法 一种 是否      更新时间:2023-10-16

我不确定其他人是否曾在许多代码中使用它的临时名称,例如,您需要访问几个类的东西深层,而不是一遍又一遍地链接会员访问操作员,而是使用一个较短的名为临时的。我尝试做类似以下操作:

struct Car
{
    struct
    {
        struct
        {
            int height, width, depth;
        } physicalInfo;
    } information;
} objectWithARatherLongName ;
int main()
{
    auto lambda1 = [] { return objectWithARatherLongName.information.physicalInfo.height; };
    // Create a temporary for a shorter name
    auto& dimens = objectWithARatherLongName.information.physicalInfo;
    auto lambda2 = [=] { return dimens.height; };
    // Have to capture "dimens" because it's a local variable
    // And over and over again, the shorter way is preferred.
}

在这种情况下,自动尺寸是临时命名的简短尺寸,但是由于我想在lambda中使用它,因此我需要捕获它,这让我让我认为我应该只使用全局名称。有没有办法以我描述但仍在使用全局变量的方式缩短这一点?我想到了只能与类型一起使用的Typedef吗?没有实际对象。

不要使用全局变量,但是如果必须,则可以添加更多:

struct Car
{
    ...
} objectWithARatherLongName ;
auto& dimens = objectWithARatherLongName.information.physicalInfo;
int main() { // ...