繁体   English   中英

在lambda函数中捕获静态成员变量

[英]Capturing static member variable inside lambda function

我想知道是否可以在lambda函数内部捕获类的static member variable (lambda函数在同一类的静态成员函数内使用)。

我一直在尝试以下操作,但无法编译代码:

  #include<string>
  #include<iostream>

  using namespace std;

  class test_temp
  {
          public:
              static string name;
              static int count_of_letters();
  };

  string test_temp::name="Vishal";
  int test_temp::count_of_letters()
  {
        auto result = [&test_temp::name]() {return(test_temp::name.size());};

  }

  int main() {
  int res=test_temp::count_of_letters();
  cout<<endl<<res<<endl;
  }

有没有办法以这种方式捕获静态成员变量?

修改后的代码(进行建议的更改后)

#include<string>
#include<iostream>

using namespace std;

class test_temp
{
        public:
            static string name;
            static int count_of_letters();
};

string test_temp::name="Vishal";
int test_temp::count_of_letters()
{
        auto result = []() {return(name.size());};
        result();
}

int main() {
int res=test_temp::count_of_letters();
cout<<res<<endl;
}

不需要捕获静态存储变量(例如静态成员)。 只需删除捕获,它将起作用。 由于您在成员函数中,因此您也不需要限定范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM