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

            Bug ID: 86610
           Summary: non-const operator erroneously called in lambda in
                    templated function
           Product: gcc
           Version: 8.1.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: daibane at sandia dot gov
  Target Milestone: ---

The following code fails to compile, saying that the non-const operator[] is
being called. GCC 7.3, Clang 6.0.0, Intel 18, and MSVC 2018 Pre all compile
this code without error. Removing either the templatization of the classify2
function or the lambda around the statement allows the code to compile without
error.


#include <initializer_list>
#include <new>

template <typename T, int n>
class Few {
  T array_[n];

 public:
  inline T& operator[](int i) { return array_[i]; }
  inline T const& operator[](int i) const { return array_[i]; }
  Few(std::initializer_list<T> l) {
    int i = 0;
    for (auto it = l.begin(); it != l.end(); ++it) {
      new (array_ + (i++)) T(*it);
    }
  }
  inline Few() {}
  inline ~Few() {}
  inline Few(Few<T, n> const& rhs) {
    for (int i = 0; i < n; ++i) new (array_ + i) T(rhs[i]);
  }
};

template <int dim>
void classify2(Few<double, 3> l) {
  double* p = new double[1];
  auto f = [=]() {
    p[0] = l[0];
  };
  f();
  delete [] p;
}

static void classify_box(double x, double y, double z) {
  Few<double, 3> l({x, y, z});
  classify2<3>(l);
}

int main() {
  classify_box(1.0, 1.0, 1.0);
}



Here is the compile error:


bug.cpp: In instantiation of ‘void classify2(Few<double, 3>) [with int dim =
3]’:
bug.cpp:36:17:   required from here
bug.cpp:28:10: error: passing ‘const Few<double, 3>’ as ‘this’ argument
discards qualifiers [-fpermissive]
     p[0] = l[0];
bug.cpp:9:13: note:   in call to ‘T& Few<T, n>::operator[](int) [with T =
double; int n = 3]’
   inline T& operator[](int i) { return array_[i]; }
             ^~~~~~~~

Reply via email to