开发者

Why mutable lambda with pointer to member function?

I'd like to get my muck开发者_开发知识库y paws on the operator() of a lambda function. The following seems up the task:

template <typename F>
void bar(F func) {
  void (F ::*pm)();
  pm = &F::operator();
}

However, in the following, I need to include the mutable keyword. Why is that? Is it possible to above instead declare a pointer to member function, which can target arbitrary lambdas?

int main(int argc, char *argv[])
{
  bar([]() mutable {});
  return 0;
}


According to 5.1.2 of the N3291 C++0x specification, the lambda's operator() is const unless you explicitly declare it mutable:

This function call operator is declared const (9.3.1) if and only if the lambda- expression’s parameter-declaration-clause is not followed by mutable.

You may be able to do some template metaprogramming magic to detect which is which.

However, it should be noted that, once func goes out of scope, you can't use that member pointer anymore. And it is a member pointer, not a function pointer, so you can't convert between the two.


C++0x lambdas are const by default, unlike the rest of the language. Consequently, your member-function variable must be const as well. The following should work:

template<typename F>
void bar(F func) {
    typedef void (F::*pm_t)() const;
    pm_t pm = &F::operator();
}


Consider this:

int x=0;
auto show = [x]() mutable
{
        x++;
};

show();

The variable 'x' is being captured by-value, and without mutable, you cannot modify the local copy of this variable. Specify mutable to enable modification of this local copy. For by-value captures, it doesn't matter if value is modified, the original x variable won't be modified.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜