I noticed something rather strange while writing C++20 related to spaceship operators.
As I understand, since C++20, comparison operators are automatically generated by the compiler. However, I have encountered an interesting problem with this automatic generation of operators.
In the code below, I am trying to define MyIterator which is derived from vector<int>::iterator.
Now I want the base class to be protected and expose functions explicitly.
So naturally, I use using declarations to use member functions from the base class.
However, the compiler complains that operator!= is missing!
Does this happen because the automatically generated operators are "generated too late"?
Interestingly, the workaround shown in the definition of MyIterator2 seems to fix the problem.
I would like to hear the cause of this weird behavior. Is this the intended behavior for automatically generated operators via the spaceship operator? Or is this a compiler bug or an unimplemented feature?
Compiler version information:
[hoge@foobar]$ clang++ --version
clang version 10.0.1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Code (main.cpp):
#include <vector>
using MyVec = std::vector<int>;
/// Does not compile
class MyIterator : protected MyVec::iterator {
using Base = MyVec::iterator;
// Error
// No member named 'operator!=' in '__gnu_cxx::__normal_iterator<int *,
// std::vector<int, std::allocator<int>>>'clang(no_member)
using Base::operator!=;
};
/// Compiles
class MyIterator2 : protected MyVec::iterator {
using Base = MyVec::iterator;
/// A rather ugly workaround!
auto operator!=(const MyIterator2 &o) const {
return static_cast<const Base &>(*this) != static_cast<const Base &>(o);
}
};
Additional notes:
GCC also rejects the code in the same way.
[hoge@foobar tmp]$ g++ --version
g++ (GCC) 10.2.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[hoge@foobar tmp]$ g++ main.cpp
main.cpp:12:23: error: ‘operator!=’ has not been declared in ‘__gnu_cxx::Base’
12 | using Base::operator!=;
|