以通用方式在某些类之间共享不同对象的最佳方式是什么?
例如,类 A 可以将对象 o 与字符串作为键存储在寄存器中,类 B 可以使用该键访问它。
我的第一个想法是创建一个寄存器(单例),它有一个哈希表作为成员,使用字符串作为键,空指针作为值。但是必须有更好的解决方案吗?
最佳答案
根据您的说明:
template <typename OB>
class A {
std::unordered_map<std::string, OB> hash;
public:
OB const& get(std::string const&) const;
void add(OB const& object, std::string const&);
};
也就是说,A<int>
是一个存储 int
的类按名称的对象,和 A<std::set<float>>
是一个按名称存储 float 集的类。你不能把它们混在一起。这符合基本的 C++ 哲学:theA.get("foo")
的类型是在编译时确定的,而不是由您在运行时输入的内容决定的。
在 C++ 中,您可以“混合”多个派生类型,如果您的特定情况需要这样做。这有点复杂:
template <typename Base>
class A {
std::unordered_map<std::string, std::unique_ptr<Base>> hash;
public:
Base const& get(std::string const&) const;
template<typename Derived> void add(std::string const& name, Derived const& object)
{
std::unique_ptr<Base> copy(new Derived(object));
hash.emplace(std::make_pair(name, std::move(copy)));
}
};
这里有一些小技巧,如 hash
应该是拷贝的唯一所有者,但它是在外部构建的,因此需要将其移动。 (为了更有趣,我可以添加一个 Derived&&
重载来消除该拷贝)
关于c++ - 如何在一些类之间共享不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9975859/