I have a class Parent
that loads configuration data from a file and creates Child
objects in a std::map
. The Child
objects are mapped by a const char*
that is defined in the configuration file. For any given Parent
, all of the children will share the same key length. So, one Parent
's mapped Child
objects may have 8-byte keys and another Parent
's kids may use 4-byte keys.
How is it possible, either using the method described here, or using another method, to create a new std::map
member object with a comparison function that depends on data only available at runtime?
Specifically, I'm trying to use memcmp(a, b, n);
like the previously linked question shows, but I want n
to be variable instead of fixed at 4.
If I haven't explained well enough what I'm trying to do, I'll try to put it in code. How do I write thecompareKey
so that it uses childKeyLength
to compare the map keys:
class Child;
class Parent {
private:
struct compareKey {
bool operator()(char * const a, char * const b) {
return memcmp(a, b, childKeyLength) < 0;
}
};
std::map<const char*, Child, compareKey> children;
size_t childKeyLength;
public:
Parent(size_t childKeyLength)
: childKeyLength(childKeyLength) {};
}