简体   繁体   中英

Capturing static member variable inside lambda function

I want to know if I can capture a static member variable of a class inside the lambda function(The lambda function is being used inside a static member function of the same class).

I've been trying the following but I'm not able to compile the code:

  #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;
  }

Is there any way to capture the static member variable in this way?

Modified Code(after doing the suggested changes)

#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;
}

Static storage variables such as static members do not need to be captured. Simply remove the capture and it will work. You don't need to qualify the scope either, since you're in a member function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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