gpt4 book ai didi

c++ - 单例模板设计问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:20:52 26 4
gpt4 key购买 nike

我目前正在使用以下简单的单例类:

template<class T>
class singleton
: boost::noncopyable
{
public:
static T& get_instance()
{
assert(sm_instance != nullptr);
return *static_cast<T*>(sm_instance);
}

protected:
singleton()
{
assert(sm_instance == nullptr);
sm_instance = this;
}
virtual ~singleton()
{
assert(sm_instance != nullptr);
sm_instance = nullptr;
}

private:
static singleton<T>* sm_instance;
};

template<class T> singleton<T>* singleton<T>::sm_instance = nullptr;


class example_one
: public singleton<example_one>
{
static example_one instance;
};

example_one example_one::instance;


class example_two
: singleton<example_two>
{
static example_two instance;
};

example_two example_two::instance;


// Usage:
example_one& x = example_one::get_instance();
example_two& y = example_two::get_instance(); // not accessible because 'example_two' uses 'private' to inherit from 'singleton<T>'

但是,我想调整一些东西。我不喜欢 get_instance() 被继承到派生类。

我想做这样的事情(非工作代码):

template<class T>
T& get_singleton();

template<class T>
class singleton
{
friend T& get_singleton()
{
assert(sm_instance != nullptr);
return *static_cast<T*>(sm_instance);
}
}

// Usage:
example_two& x = get_singleton<example_two>();

最佳答案

如果你打算使用模板函数,为什么还要费心于基类:

template<typename T>
T& getInstance()
{
static T instance;
return instance;
}

class example_one: boost::noncopyable
{
example_one() {} // Note private construtor
friend example_one& getInstance<example_one>();
};

class example_two: boost::noncopyable
{
example_two() {}
friend example_two& getInstance<example_two>();
};

关于c++ - 单例模板设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7833319/

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