Shami Shariff
Shami Shariff

Reputation: 1

c++11 for_each with lambda as member function

I am facing the compilation error when using lambda with member function in for_each loop. please the below code snippet for reference.

void CCommConfig::AddAllowedIP(const string& strIp)
{
if (!strIp.empty())
m_allowedIpsList.push_back(strIp);
}
void CCommConfig::AddAllowedIpList(STRING_LIST &lstIps)
{
std::for_each(begin(lstIps), end(lstIps), this->AddAllowedIP);
}

Errors listed as

1>........\Source\Lib\cci\src\CommConfig.cpp(70): error C3867: 'CCommConfig::AddAllowedIP': non-standard syntax; use '&' to create a pointer to member 1>........\Source\Lib\cci\src\CommConfig.cpp(70): error C2672: 'std::for_each': no matching overloaded function found

Upvotes: 0

Views: 107

Answers (1)

kmdreko
kmdreko

Reputation: 60797

You cannot use this->AddAllowedIP to get a function object to call CCommConfig::AddAllowedIP with this, that is simply not allowed. You can get a pointer to the function via &CCommConfig::AddAllowedIP but that doesn't help you because it needs a CCommConfig to call it from.

You should create a lambda:

[this](const string& ip){ this->AddAllowedIP(ip); }

or you can use std::bind (though it's fallen out of favor):

std::bind(&CCommConfig::AddAllowedIP, this, std::placeholders::_1)

Both will create a function object that will properly call AddAllowedIP with this on your behalf so you can pass it to for_each.

Edit: looking at it again, you might just be better off with a loop:

for (const string& ip : lstIps)
  AddAllowedIP(ip);

Upvotes: 4

Related Questions