簡體   English   中英

C++11 Lambda 成員方法內的函數繼承 scope

[英]C++11 Lambda Functions inside member methods inherit scope

我寫了一個 function foreach接受 lambda function ala:

void foreach(void (*p)(pNode))
{ /* ... */ }

如果我從主循環傳遞一個 lambda function ,它會按預期工作:

int a = 5;
env.N().foreach
(
    [&](pNode n)->void
    {
        n->tps(a); 
    }
);

However, if I try to call the same function from within a member method, the lambda function "inherits" the scope of the member function and generates a compiler error. 例如,如果我嘗試將其包含在 class Object的成員方法中,命名為method() ,我會收到以下錯誤:

error: no matching function for call to ‘IDSet<Node>::foreach(Object::method()::<lambda(pNode)>)’
note: candidate is: void IDSet<T>::foreach(void (*)(IDSet<T>::pT)) [with T = Node, IDSet<T>::pT = pNode]

I realize this is the compiler being safe, since I could include instance-specific variables inside the lambda function, in which case the lambda would need to be scoped, however I'm wondering if it's possible to make this lambda "static".

我嘗試了reinterpret_cast ,但是這給了我這個錯誤:

error: invalid cast from type ‘Object::method()::<lambda(pNode)>’ to type ‘void (*)(pNode)’

[&](pNode...之前指定static ... 似乎也不是有效的語法。

絕望地,我還嘗試將[&]更改為[=][][a] ,但都沒有奏效。

Does anyone know if there is a way to do accomplish my goal of creating a "static" lambda function, or at any sort of lambda function that will be accepted for that matter?

謝謝!


回答:

Cat Plus Plus的幫助下,我能夠打開我不正確的代碼:

void foreach(void (*p)(pT))
{
    for(pTiter i = _map.begin(); i != _map.end(); i++)
    {
        (*p)(i->second);
    }
}

成功能齊全的代碼:

void foreach(std::function<void(pT)>(p))
{
    for(pTiter i = _map.begin(); i != _map.end(); i++)
    {
        p(i->second);
    }
}

這完全符合我的要求。

好吧,你不能使用指針。

void foreach(std::function<void(pNode)>);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM