c++ - 跨文件共享 map C++

标签 c++

我有一个用例,我必须创建函数指针映射并将其用于各种文件。我已经在头文件中编写了模板代码以及填充 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 (没有staticextern)。

请注意,通常不鼓励使用全局变量。

关于c++ - 跨文件共享 map C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53663724/

相关文章:

c++ - C++ 字符串中的字符串游标/标记

c# - 从 C++ 调用 C# 事件

c++ - clang 的全局构造函数警告是否过于严格?

c++ - 如何查找字符串是否与数组中找到的字符串匹配?

c++ - 编译时报错C2676

c++ - 挣扎着将新内容分配给 vector 的指针

c++ - 初始化对象时出现段错误

c++ - 处理所有二次公式结果

c++ - 成对函数评估算法(C++、STL)

具有范围解析和条件的 C++ 三元运算符