Sep 25, 2014

[C++11] decltype(captured var) inside lambda expression

trap.

We would consider the lambda expression generated below:

void fun()
{
    static int a;

    int local_var = 42;

    [&local_var]{
        decltype(local_var) var_1 = 42;
    }();
}

equals to:

void fun()
{
  static int a;

  int local_var = 42;
  
  struct Lambda
  {
      int& local_var;

      Lambda(int& _local_var):local_var(_local_var){}

      void operator()() const
      {
          decltype(local_var) var_1 = 42; // won't compile
      }

  };
  
  Lambda{local_var}();
}
but not quite.

decltype(local_var) within the lambda expression is the type
of local variable local_var, which is int.

Local type Lambda's decltype(local_var)
is the type of l-value reference to int, which can't bind
to r-value 42.

While considering lambda expression
 'is equal to' type Lambda,
that's not exact the case for decltype(local_var) inside lambda expression.

decltype(local_var) is the type of outer scope's local_var,
i.e int.
(transformation not considered) 
reference: C++11 ISO14882-2011 , i.e : 5.1.2.18

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.