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
KenC
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 to share