tags:

views:

91

answers:

3

Hi, I have a class like this:

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

The data member must use different comparison function according to Mode argument.

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

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

thanks.

+1  A: 

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

workmad3
+1  A: 

You can use the same compare predicate, as for map.

class MyClass
{
    CompFunc cmp;
    map<int, std::string, CompFunc> data;
public:
    MyClass(int Mode) : cmp( get_cmpfunc(Mode) ), data(cmp) {...}
    bool operator == (...)
    {
        cmp(...);
    }
};
Lazin
+4  A: 
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;
};
James Hopkin