gpt4 book ai didi

c++ - 如何在不授予私有(private)成员访问权限的情况下在 C++ 中隐藏 STL 仿函数结构

转载 作者:行者123 更新时间:2023-11-30 05:32:24 24 4
gpt4 key购买 nike

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

最佳答案

为什么不使用 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>

关于c++ - 如何在不授予私有(private)成员访问权限的情况下在 C++ 中隐藏 STL 仿函数结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com