我有一个用例,我必须创建函数指针映射并将其用于各种文件。我已经在头文件中编写了模板代码以及填充 map 的代码。当我没有将 map 定义为静态时,我收到一条错误消息,指出 map 的多个定义,因为我将此 header 包含到多个 cpp 文件中。为避免这种情况,我将 map 创建为静态。但是,现在程序因段错误而失败,可能是因为当我开始添加函数时 map 尚未初始化。我怎么解决这个问题?
头文件-
#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
编辑:
我还尝试创建一个结构,将 map 作为静态成员变量来避免使用全局变量。即使那样似乎也行不通。
最佳答案
当您将变量定义为 static
时,这意味着 internal linkage ,这使得它对每个 translation unit 都是私有(private)的.
即每个源文件都有自己独特的 map 实例。
要使 map 成为全局 map 并在所有翻译单元之间共享,只需声明 map (使用extern
而不是static
)。并在单个 源中定义 map (没有static
或extern
)。
请注意,通常不鼓励使用全局变量。
关于c++ - 跨文件共享 map C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53663724/