摘要:如何在 C++ 中创建单例 mixin?我试图避免复制相同的get_instance()
函数、私有构造函数等。但我想不出一种方法来使它成为 mixin,因为静态实例将由从 mixin 继承的所有东西共享。
使每个派生类成为单例很容易,但是有没有办法在不重复代码的情况下做到这一点?非常感谢您的帮助,我很难过。
代码:
我正在编写一个带有Registry
类的程序,用于按名称查找对象。
#include <string>
#include <memory>
#include <map>
#include <string>
#include <assert.h>
template <typename T>
class Registry
{
private:
// make private so that the class can't be instantiated and must be used via get_instance
Registry() {}
protected:
std::map<std::string, std::shared_ptr<T> > name_to_object_ptr;
public:
static Registry<T> & get_instance()
{
static Registry<T> instance;
return instance;
}
void register_name(const std::string & name, T*obj_ptr)
{
assert( name_to_object_ptr.count(name) == 0 );
name_to_object_ptr[name] = std::shared_ptr<T>(obj_ptr);
}
const std::shared_ptr<T> & lookup_name(const std::string & name)
{
assert( name_to_object_ptr.count(name) > 0 );
return name_to_object_ptr[name];
}
int size() const
{
return name_to_object_ptr.size();
}
};
我的Registry
班级是单身人士;它必须是一个单例(这样注册的对象就不会消失)。
class DerivedRegistryA : public Registry<int>
{
};
class DerivedRegistryB : public Registry<int>
{
};
int main()
{
DerivedRegistryA::get_instance().register_name(std::string("one"), new int(1));
std::cout << DerivedRegistryA::get_instance().size() << std::endl;
DerivedRegistryA::get_instance().register_name(std::string("two"), new int(2));
std::cout << DerivedRegistryA::get_instance().size() << std::endl;
DerivedRegistryA::get_instance().register_name(std::string("three"), new int(3));
std::cout << DerivedRegistryA::get_instance().size() << std::endl;
DerivedRegistryB::get_instance().register_name(std::string("four"), new int(4));
std::cout << DerivedRegistryB::get_instance().size() << std::endl;
return 0;
}
输出:
1
2
3
4
期望的输出:
1
2
3
1