Comparison function of an associated container item in a class

I have a class like this:

class MyClass{
public:
    MyClass(int Mode);
private:
    std::map < int, std::string, CompFunc > data;
};

      

The item must use a different comparison function according to the Mode argument.

if Mode == 1, then use CompFunc1.
if Mode == 2, then use CompFunc2.
etc.

      

but the CompFunc template argument is fixed there, how can I make it dynamically?

thanks.

0


a source to share


3 answers


struct Cmp
{
    explicit Cmp(int mode) : mode_(mode) {}

    bool operator()(int lhs, int rhs) const
    {
        switch (mode_)
        {
            case 1: return CompFunc1(lhs, rhs); break;
            case 2: return CompFunc2(lhs, rhs); break;
            // etc.
        }
    }

private:
    int mode_;
};

class MyClass
{
public:
    explicit MyClass(int Mode) : cmp(mode), data(cmp) {}
private:
    Cmp cmp;
    std::map<int, std::string, Cmp> data;
};

      



+4


a source


You can use the same comparison predicate as for the map.



class MyClass
{
    CompFunc cmp;
    map<int, std::string, CompFunc> data;
public:
    MyClass(int Mode) : cmp( get_cmpfunc(Mode) ), data(cmp) {...}
    bool operator == (...)
    {
        cmp(...);
    }
};

      

+1


a source


Write a wrapper class / function that conforms to the correct interface, but dispatches the correct function depending on the mode (or other variables).

0


a source







All Articles