如何仅在特定类中限制类的实例化?
我不想在单个文件中限制它,因此匿名命名空间不适合我.
请注意,我想让整个世界都可以看到要限制的类的声明,只是来自整个世界的一个特定候选者只能实例化它.
我怎样才能做到这一点?
Rak*_*111 11
用friend
s!使一个班级成为班级Foo
的朋友Bar
意味着Foo
可以访问Bar
私人会员.如果您将构造函数Foo
设为私有,则只能创建一个实例Bar
.
struct restricted_t {
friend struct allowed_t; // allow 'allowed_t' to access my private members
private:
// nobody can construct me (except for my friends of course)
restricted_t() = default;
};
struct allowed_t {
restricted_t yes; // ok
};
struct not_allowed_t {
restricted_t no; // not ok
};
int main() {
allowed_t a; // ok, can access constructor
not_allowed_t b; // error, constructor is private
}
Run Code Online (Sandbox Code Playgroud)
你可以采用密钥模式(借用Rakete1111的例子):
class pass_key { friend class allowed_t; pass_key() {} };
struct restricted_t
{
restricted_t(pass_key);
};
class allowed_t
{
public:
allowed_t() : yes(pass_key()) {} // ok, allowed_t is a friend of pass_key
private:
restricted_t yes;
};
class not_allowed_t
{
public:
not_allowed_t() : no(pass_key()) {} // not ok, pass_key() is private
private:
restricted_t no;
};
int main()
{
allowed_t a; // OK, can access constructor
not_allowed_t b; // ERROR, only a friend of the key
// class has access to the restricted
// constructor
}
Run Code Online (Sandbox Code Playgroud)
该模式允许比制作restricted_t
朋友更精细的访问控制,allowed_t
并避免复杂的代理模式.