c++ - 有没有一种方法可以在不捕获 lambda 变量的情况下编写更短的代码?

标签 c++ lambda global capture

我不确定是否有人会在多行代码中使用时使用更短的名称来临时创建临时名称,例如,您需要访问几个类深处的内容,而不是链接成员访问运算符一遍又一遍,您将只使用一个较短的命名临时文件。我尝试执行以下操作:

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.
}

在这种情况下,auto dimens 是临时命名的简称,但由于我想在 lambda 中使用它,我需要捕获它,这让我觉得我应该只使用全局的全名。有没有办法按照我描述的方式缩短它但仍然使用全局变量?我想到了一个只适用于类型的 typedef,对吧?不适用于实际物体。

最佳答案

不要使用全局变量,但如果必须,您可以再添加一个:

struct Car
{
    ...
} objectWithARatherLongName ;
auto& dimens = objectWithARatherLongName.information.physicalInfo;

int main() { // ...

关于c++ - 有没有一种方法可以在不捕获 lambda 变量的情况下编写更短的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741630/

相关文章:

c++ - malloc:无效指针从空闲列表中出队

Java 8 重新映射修改值

javascript箭头函数: can we capture values like in c++ lambdas?

c++ - (预处理器)C++ 中的全局变量错误

SharePoint wsp 解决方案 : How to Deploy Globally

c++ - 在 VS 中构建由 Boost 驱动的解决方案

c++ - Ref 限定的成员函数的目的是什么?

c++ - 无法使用 GCC 5.1 工具链编译 C++11 源代码

python - 带有额外未传递变量的python中的lambda

python - 传播应用程序设置