如何在不授予私有成员访问权限的情况下隐藏 C++ 中的 STL 函子结构

How to Hide STL Functor Structs in C++ Without Granting Private Member Access

本文关键字:C++ 隐藏 情况下 中的 STL 结构 权限 访问权 访问 成员      更新时间:2023-10-16

我有一个类,它将项目存储在 std::unordered_map 中。 映射的键是自定义类型,因此我有一个帮助程序结构,定义如下:

struct hash_equ {
    // Hasher
    size_t operator()(myType const &val) const;
    // Equality comparer
    bool operator()(myType const &a, myType const &b) const;
};

然后,在类声明中,我有以下内容:

class Foo {
private:
    typedef std::unordered_map<myType const &, int, hash_equ, hash_equ> map_type;
    map_type _myMap;
    ...
};

问题是我想从 Foo.cpp 外部的代码中隐藏hash_equ的存在,但必须在 Foo.h 中定义hash_equ才能声明成员Foo::_myMap。 我能想到的唯一想法是将hash_equ声明为一个私有的、内部的Foo类。 但是,在 C++11 中,这样做将授予Foo私有成员访问hash_equ 的权限。 有没有办法对客户端隐藏hash_equ,同时阻止访问Foo的私人成员?

为什么不使用私有的实现命名空间?

// This can be in either Foo.h or in a file included by it 
namespace detail
{
    struct hash_equ 
    ...
}

然后像这样使用它:

typedef std::unordered_map<
    myType const &, 
    int, 
    detail::hash_equ, 
    detail::hash_equ>