c++stdset

How to refer to the enclosing class member variables from inside of a nested class instance?


As a class member of some class A, I would like to maintain an std::set storing Bs. The set uses a custom comparison object which needs to read a non-static class member, m_t in the example code below, to perform its comparison.

Example code:

class B { ... };

class A {
    struct Comp {
        bool operator()(B b1, B b2) const {
            // ... compares b1 and b2, uses m_t
        }
    };
    std::set<B, Comp> m_set;
    double m_t;
};

Unfortunately this does not compile as understandably we cannot access a non-static member of A within Comp. Is there some other way to achieve this? I would like to avoid making m_t static.

(Some background for context: this is for implementing a sweep line algorithm. Specifically, B implements a function dependent on m_t, where m_t varies between 0 and 1. The functions do not intersect within [0, 1], so the comparisons between Bs never change, thus keeping the std::set valid. With the sweepline at a given m_t, I then need to query with a given value which functions in the set surround it.)

Edit: I had already seen the question this is now marked as a duplicate to, Using custom std::set comparator. The answers there do explain how to make a custom comparator, but have nothing to do with referring to another class member.


Solution

  • Comp is just a C++ class, so you can complement it with any data as needed. E.g. a pointer to the enclosing class instance:

    struct A {
        
        struct Comp {
            A *host;
            
            bool operator()(B b1, B b2) const {
                std::cout << host->m_t << std::endl;
                // ...m_t is accessible here
            }
        };
        
        double m_t;
        std::set<B, Comp> m_set{ Comp { this } };
        
    };