a.h
#ifndef _A__
#define _A__
class A {
public:
struct Less {
bool operator() (const A* const &k1, const A* const &k2) const
{
return k1->_a < k2->_a;
}
};
A(int a) : _a(a)
{
;
}
virtual ~A()
{
;
}
private:
int _a;
};
#endif
b.h
#ifndef _B__
#define _B__
#include "a.h"
class B : public A {
public:
B(int a) : A(a)
{
;
}
~B()
{
;
}
};
#endif // _B__
c.cpp
#include <set>
#include "a.h"
class B;
class C
{
std::set<B*, A::Less> _set;
};
When c.cpp is compile with g++ 8.1, it fails to compile with this static check error
/export/dev6/rajpal/gcc/8.1.0/bin/g++ -c c.cpp
In file included from /export/dev6/rajpal/gcc/8.1.0/include/c++/8.1.0/set:60,
from c.cpp:1:
/export/dev6/rajpal/gcc/8.1.0/include/c++/8.1.0/bits/stl_tree.h: In instantiation of 'class std::_Rb_tree<B*, B*, std::_Identity<B*>, A::Less, std::allocator<B*> >':
/export/dev6/rajpal/gcc/8.1.0/include/c++/8.1.0/bits/stl_set.h:133:17: required from 'class std::set<B*, A::Less>'
c.cpp:6:25: required from here
/export/dev6/rajpal/gcc/8.1.0/include/c++/8.1.0/bits/stl_tree.h:452:21: error: static assertion failed: comparison object must be invocable with two arguments of key type
static_assert(__is_invocable<_Compare&, const _Key&, const _Key&>{},
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I understand error is because at compile time, compiler is not able to determine how to compare _Key=B*
and if I make available definition of B
, it should work just fine.
But, my question is if there is any way to tell compiler that B
is actually derived from A
and there is a way to compare A
objects.
Also please note that I don't want to change std::set<B*, A::Less>
to std::set<A*, A::Less>
which should also fix this problem.