【问题标题】:How to Hide STL Functor Structs in C++ Without Granting Private Member Access如何在不授予私有成员访问权限的情况下在 C++ 中隐藏 STL 函子结构
【发布时间】:2016-05-10 16:45:36
【问题描述】:

我有一个类,它将项目存储在 std::unordered_map 中。 map 的 key 是自定义类型,所以我有一个 helper struct 定义如下:

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的存在,但是hash_equ必须定义在Foo.h中为了声明成员Foo::_myMap。我能想到的唯一想法是将hash_equ 声明为Foo 的私有内部类。但是,在 C++11 中,这样做会将对 Foo 私有成员的访问权限授予 hash_equ。有什么方法可以对客户端隐藏hash_equ,同时防止访问Foo 的私人成员?

【问题讨论】:

  • 您可以将其隐藏在 details 命名空间中。如果您不是实施者,则 SOP 不会访问详细信息命名空间中的任何内容。
  • 这不是PIMPL 的好处吗?

标签: c++ c++11 stl


【解决方案1】:

为什么不使用private, implementation, namespace?

// 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> 

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2014-08-09
    • 2020-01-04
    • 2013-10-16
    • 2022-06-28
    • 1970-01-01
    相关资源
    最近更新 更多