I have a use case where I've to create a map of function pointers and use it across various files. I've written the code for the template in a header file, along with the code to fill the map. When I don't define map as static, I get an error saying multiple definitions of the map because I include this header into multiple cpp files. To avoid that, I created map as static. However, now the program fails with Seg Fault probably because map is not yet initialized when I started adding the functions. How can I solve this problem?
Header file -
#ifndef KEY_COMPARE__H
#define KEY_COMPARE__H
#include <map>
enum DataType {
A,
B,
MaxType
};
static const int MAX_KEYS = 5;
typedef bool (*Comparator)(uint8*, uint8*);
static std::map<long, Comparator> ComparatorMap; // <--- This is the map
template<typename T, typename... Args>
long GetComparatorKey(T first, Args... args) {
// Code to return a unique key based on first, args...
}
template <int N, DataType T, DataType... Ts>
struct Comparator {
Comparator() {
long comparatorKey = GetComparatorKey(T, Ts...);
ComparatorMap[comparatorKey] = c1Func; // Seg fault here
}
static bool Compare(uint8 *rec1, uint8 *rec2){
// Function to compare
}
static const size_t nKeys_ = Comparator<N+1, T, Ts...>::nKeys_ - 1;
Comparator<N+1, A, T, Ts...> ci_;
Comparator<N+1, B, T, Ts...> cs_;
bool (*c1Func)(uint8*, uint8*) = Compare;
};
/// Other code for base cases and stop recursion
#endif // KEY_COMPARE__H
Edit:
I've also tried to create a struct with map as static member variable to avoid global variables. Even that doesn't seem to work.