我不确定我是否正确理解你的问题,但对我来说,单身人士的“集合”是无关紧要的。你有一个固定数量的单例,称它们为Singleton1
至SingletonX
,其中X
在编译时已知。这对线程无关紧要。
对于实际的单例,您可以让它们从处理每个线程部分的单个模板化基类继承。事情是这样的:
template<class B>
struct SingletonBase
{
static B &getInstance()
{
// One instance per thread
static std::unordered_map<std::thread::id, B> intances;
if (instances.find(std::this_thread::get_id()) == instances.end())
instances[std::this_thread::get_id()] = B{};
return instances[std::this_thread::get_id()];
}
};
class Singleton1 : public SingletonBase<Singleton1>
{
// ...
};
如果你不想为单身分开不同的类,你可以使用std::array
来存储它们:
class Singleton : public SingletonBase<Singleton>
{
// ...
};
std::array<Singleton, X> singletons;
这将创建一个指定号码X
数组编译时间,并可以像普通数组一样访问:Singleton &instance = singletons[0].getInstance();
。
请注意,我的示例代码使用“新”C++ 11标准库中的功能。
这是不可能的模糊和不明确的 - 甚至不清楚问题是什么。 – 2012-07-19 08:12:15