https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65885

            Bug ID: 65885
           Summary: lambda expressions in templates fail to capture `const
                    int' variables
           Product: gcc
           Version: 5.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: myoga.murase at gmail dot com

The following c++11 code does not compile with gcc-5.1.0 while it is fine with
gcc-4.9.2, and gcc-4.8.3.

[user@host gcc]$ cat lambda.cpp
int gvar=1;

template<int I>
void tfun(){
  int const var=gvar;
  auto f=[=](){return var*var;};
}

void fun(){
  tfun<1>();
}
[user@host gcc]$ /home/user/opt/gcc/5.1.0/bin/g++-5.1 -v
Using built-in specs.
COLLECT_GCC=/home/user/opt/gcc/5.1.0/bin/g++-5.1
COLLECT_LTO_WRAPPER=/home/user/opt/gcc/5.1.0/libexec/gcc/x86_64-unknown-linux-gnu/5.1.0/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with: ./configure --program-suffix=-5.1
--prefix=/home/user/opt/gcc/5.1.0 --with-gmp=/home/user/local
--with-mpfr=/home/user/local --with-mpc=/home/user/local --disable-libjava
Thread model: posix
gcc version 5.1.0 (GCC)

[user@host gcc]$ /home/user/opt/gcc/5.1.0/bin/g++-5.1 -std=c++11 -c lambda.cpp
lambda.cpp: In instantiation of 'tfun()::<lambda()> [with int I = 1]':
lambda.cpp:6:12:   required from 'struct tfun() [with int I = 1]::<lambda()>'
lambda.cpp:6:31:   required from 'void tfun() [with int I = 1]'
lambda.cpp:10:11:   required from here
lambda.cpp:6:26: error: redeclaration of 'const int var'
   auto f=[=](){return var*var;};
                          ^
lambda.cpp:6:26: note: 'const int var' previously declared here
lambda.cpp: In instantiation of 'void tfun() [with int I = 1]':
lambda.cpp:10:11:   required from here
lambda.cpp:6:10: sorry, unimplemented: non-trivial designated initializers not
supported
   auto f=[=](){return var*var;};
          ^

I also tried with the options, `-Wall -Wextra' and `-fno-strict-aliasing
-fwrapv -fno-aggressive-loop-optimizations', but nothing changed. The error is
also reproduced with the latest version of GCC:
http://melpon.org/wandbox/permlink/yOs7mqpdpKKGNllN

The error seems to occur in the following situation:
 - A lambda expression is in a function template or a class template.
 - A variable of `const int' is implicitly captured with `[=]' or `[&]'.
(Interestingly, the error is not reproduced with `const double' or `int'
variables.)
 - The variable is used more than once in the lambda expression.
 - The variable is initialized with a non-constant value (which cannot be
statically determined).

This may be related to
Bug 64791 (RESOLVED FIXED) https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64791

Reply via email to