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