skellpco
skellpco

Reputation: 119

How to use custom class pointer comparator inside class being compared

I am trying to use a custom comparator as in the following minimal example:

#include <set>
using namespace std;

struct idComp;

class TestClass
{
   public:
      int id;
      void setId(int i){ id = i; }
      int getId(){ return id; }
      void test( set<TestClass*, idComp> &s){
         //do my stuff 
      }
      void test2(){
         set <TestClass*, idComp> s;
      }
};

struct idComp
{
   bool operator() (TestClass* t1, TestClass* t2) const
   {
      return t1->getId() < t2->getId();
   }
};

int main(int argc, char* argv[])
{
   return 0;
}

...but when I try to compile I get the following error relating to the test function:

comp_ref.cpp:12:34: error: ‘idComp’ was not declared in this scope
       void test( set<TestClass*, idComp> &s){
                                  ^~~~~~
comp_ref.cpp:12:40: error: template argument 2 is invalid
       void test( set<TestClass*, idComp> &s){

and this with the addition of test2:

/usr/include/c++/7/bits/stl_tree.h:708:31: error: invalid use of incomplete type ‘struct idComp’
       _Rb_tree_impl<_Compare> _M_impl;

Any suggestions of how/where to define idComp so that it is usable by the function test?

Upvotes: 0

Views: 48

Answers (1)

Reticulated Spline
Reticulated Spline

Reputation: 2012

Since you have a bit of a circular dependency, you can resolve this by forward-declaring idComp before TestClass:

struct idComp;

class TestClass
{
   ...

But you can leave the definition of struct idComp where it is.

Upvotes: 1

Related Questions