c++gccusing-directives

gcc 11.3.0 does not find operator despite using directive


The following code (a simplified example from a more complex code) fails to compile with gcc 11.3.0

#include <array>
#include <memory>
#include <tuple>

namespace tools {
  template <typename U, typename W, std::size_t N>
  void operator*=(std::array<U, N>& a, const W& b) {
    for (auto& x : a)
      x *= b;
  }
}

namespace nameA {
  template <typename Jclass>
  struct Abase {
    
    template <typename... U>
    void calc(const typename Jclass::Utype& v, typename Jclass::Wtype& out, std::tuple<U...> par) const;
  };

  template <typename Jclass>
  template <typename... U>
  void Abase<Jclass>::calc(const typename Jclass::Utype& v, typename Jclass::Wtype& out, std::tuple<U...> par) const
  {
    std::unique_ptr<Jclass> j{new Jclass};
    std::apply([&](auto&&...x) { return j->calc(v, out, x...); }, par);
  }
}

template <std::size_t N, std::size_t M>
struct outtype {
  std::array<int, N> a;
  std::array<int, M> b;

private:
  template <class F, class... ArgsType>
  void doall(F&& f, ArgsType... args) { f(a, std::forward<ArgsType>(args)...); f(b, std::forward<ArgsType>(args)...); }

public:
  void operator*=(int rhs) { doall([&](auto& el) { using tools::operator*=; el *= rhs; }); }
};

namespace nameA {
  template <typename U, typename W>
  struct Jbase {
    using Utype = U;
    using Wtype = W;
    template <typename D>
    void calc(const U& in, W& out, const D& d) const
    {
      f(in, out);
      out *= d;
    }
    virtual void f(const U& in, W& out) const = 0;
  };
}

struct J : public nameA::Jbase<std::array<int, 3>, outtype<3, 3>> {
  virtual void f(const std::array<int, 3>& in, outtype<3, 3>& out) const { out.a = in; out.b = in; }
};


int main()
{
  nameA::Abase<J> a;
  std::array<int, 3> in = { 1, 2, 3 };
  outtype<3, 3> out;
  a.calc(in, out, std::make_tuple(4));
}

I compile the code with

g++ -Wall -pedantic -std=c++17 -o test test.cpp

and the error I get is

test.cpp:40:80: error: no match for ‘operator*=’ (operand types are ‘std::array<int, 3>’ and ‘int’)
   40 |   void operator*=(int rhs) { doall([&](auto& el) { using tools::operator*=; el *= rhs; }); }

The version of g++ is 11.3.0.

This seems very strange, because I explicitly have using tools::operator*= in the lambda function passed to doall. The compiler does not give a list of candidates for operator*= either.

Link to godbolt where the code can be tested.

If I replace

void operator*=(int rhs) { doall([&](auto& el) { using tools::operator*=; el *= rhs; }); }

with

void operator*=(int rhs) { doall([&](auto& el) { tools::operator*=(el, rhs); }); }

then the code compiles with no warnings. I cannot see the difference between the two alternatives.

Also, with a newer gcc 13.1.1, the code compiles.

Is this a bug of gcc 11.3.0?


Solution

  • What you have observed is a gcc bug which is confirmed here.