https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110752
Bug ID: 110752 Summary: decltype in lambda loses const qualifier unless lambda is mutable Product: gcc Version: 13.1.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: jzwinck at gmail dot com Target Milestone: --- I believe this code should compile (and with MSVC it does), but with GCC it does not: template<typename Arg> auto & C(Arg && arg) { return arg; } void DecltypeWithinLambda() { int i = 0; [[maybe_unused]] auto l = [i]() // mutable { // does not preserve constness of 'i' within non-mutable lambda // Seems to be evaluating it as if referencing the outer 'i' // Though, decltype((i)) does do the right thing. // alternative solution to mutable is to 'rename' the captured variable list in the capture spec using T = decltype(C(i)); [[maybe_unused]] T t(C(i)); // actual use of C() only matches decltype if mutable }; } GCC says the last line is invalid: error: binding reference of type 'T' {aka 'int&'} to 'const int' discards qualifiers | [[maybe_unused]] T t(C(i)); // actual use of C() only matches decltype if mutable | ~^~~ If the lambda is marked mutable, it compiles as expected. So does this, which seems like it should be equivalent to the above: struct F { void DecltypeWithinConstMethod() const { using T = decltype(C(i)); [[maybe_unused]] T t(C(i)); // actual use of C() matches decltype } int i; }; Demo: https://gcc.godbolt.org/z/PzEodY1bW A somewhat similar bug, but not the same: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63192