实施单例包装器 class 也验证 'the singleton constructor is private'
Implementing a singleton wrapper class that also verifies 'the singleton constructor is private'
我制作了一个单例包装器模板 class,它提供 instance()
成员函数,并且还应该断言单例 class 是否具有 private
构造函数。定义如下:
template <
class T,
class = typename std::enable_if<!std::is_constructible<T>::value, void>::type
>
class singleton {
public:
static T& instance() {
static T inst;
return inst;
}
};
当我定义单例时 class 如:
class class_with_public_constr
: public singleton<class_with_public_constr> {
public:
class_with_public_constr() {}
friend class singleton<class_with_public_constr>;
};
代码通过了 enable_if
断言。我的 singleton
class 模板有什么问题?
您可以简化代码如下,并在构造函数为 public
(即不是 private
、protected
)
时打印错误
template<typename T>
class singleton
{
public:
// Below constructor is always invoked, because the wannabe singleton class will derive this class
singleton () {
static_assert(!std::is_constructible<T>::value, "the constructor is public");
}
static T& instance();
};
客户端 class 如下所示:
class A : public singleton<A>
{
friend class singleton<A>;
//public: // <---------- make it `public` & you get the error!
A() {}
};
这里是 demo.
我制作了一个单例包装器模板 class,它提供 instance()
成员函数,并且还应该断言单例 class 是否具有 private
构造函数。定义如下:
template <
class T,
class = typename std::enable_if<!std::is_constructible<T>::value, void>::type
>
class singleton {
public:
static T& instance() {
static T inst;
return inst;
}
};
当我定义单例时 class 如:
class class_with_public_constr
: public singleton<class_with_public_constr> {
public:
class_with_public_constr() {}
friend class singleton<class_with_public_constr>;
};
代码通过了 enable_if
断言。我的 singleton
class 模板有什么问题?
您可以简化代码如下,并在构造函数为 public
(即不是 private
、protected
)
template<typename T>
class singleton
{
public:
// Below constructor is always invoked, because the wannabe singleton class will derive this class
singleton () {
static_assert(!std::is_constructible<T>::value, "the constructor is public");
}
static T& instance();
};
客户端 class 如下所示:
class A : public singleton<A>
{
friend class singleton<A>;
//public: // <---------- make it `public` & you get the error!
A() {}
};
这里是 demo.