c++ Set as an class member variable with a class function object

241 views Asked by At

I need to have set as a class member variable, but also need it's comparision function object use the attributes of the class.

class Example
{
   int _member1;
   set<string, MyCmp> _myNameSet;

   class MyCmp
   {
      Example& myEx;

      MyCmp( const Example& ex) {
         myEx = ex;
      }

      bool operator() (const string& lhs, const string& rhs)
      {
         /// Use "_member1" here ...

         myEx._member1;

         /// Do something ....
      }
   }
};

So here my question is, how do i pass the Example object as an argument to the MyCmp constructor? Since the "_myNameSet" is an member variable.

If it was not an member variable, there is a way i know:

void Example::functionBlah()
{
   MyCmp obj(&(*this));
   set<String, MyCmp> myLocalSet(obj);
}
1

There are 1 answers

0
Jarod42 On BEST ANSWER

You may use initializer list in constructor:

class Example
{
public:
    Example() : _member1(0), _myNameSet(this) {}

    Example(const Example&) = delete;
    Example& operator = (const Example&) = delete;

    // Other stuff
private:
   int _member1;
   set<string, MyCmp> _myNameSet;
};