私有使用基构造函数的声明不是私有的
Private using declaration of base constructor is not private
基础构造函数的 using
声明是私有的,但仍然可以构造 class。为什么?
对于 operator[]
的 using
声明,辅助功能的工作方式不同,必须是 public.
#include <vector>
template<typename T>
class Vec : std::vector<T>
{
private:
using std::vector<T>::vector; // Works, even if private. Why?
public:
using std::vector<T>::operator[]; // must be public
};
int main(){
Vec<int> vec = {2, 2};
auto test = vec[1];
}
如果我希望构造函数是私有的怎么办?可以用 using
声明来完成吗?
基础 class 构造函数的使用声明保持与基础 class 相同的可访问性,无论基础 class 的可访问性如何。来自 [namespace.udecl]:
A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using-declarator that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored
强调
用简单的英语来说,from cppreference:
It has the same access as the corresponding base constructor.
如果你想"inherited"构造函数是私有的,你必须手动指定构造函数。您不能使用 using 声明来执行此操作。
using
reference 指出继承的构造函数
has the same access as the corresponding base constructor.
它进一步暗示了这背后的基本原理:
It is constexpr
if the user-defined constructor would have satisfied constexpr
constructor requirements. It is deleted if the corresponding base constructor is deleted or if a defaulted default constructor would be deleted
显然,您不能显式地 constexpr
或 delete
继承的构造函数,因此这些特性只是被继承。访问级别也是如此。
基础构造函数的 using
声明是私有的,但仍然可以构造 class。为什么?
对于 operator[]
的 using
声明,辅助功能的工作方式不同,必须是 public.
#include <vector>
template<typename T>
class Vec : std::vector<T>
{
private:
using std::vector<T>::vector; // Works, even if private. Why?
public:
using std::vector<T>::operator[]; // must be public
};
int main(){
Vec<int> vec = {2, 2};
auto test = vec[1];
}
如果我希望构造函数是私有的怎么办?可以用 using
声明来完成吗?
基础 class 构造函数的使用声明保持与基础 class 相同的可访问性,无论基础 class 的可访问性如何。来自 [namespace.udecl]:
A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using-declarator that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored
强调
用简单的英语来说,from cppreference:
It has the same access as the corresponding base constructor.
如果你想"inherited"构造函数是私有的,你必须手动指定构造函数。您不能使用 using 声明来执行此操作。
using
reference 指出继承的构造函数
has the same access as the corresponding base constructor.
它进一步暗示了这背后的基本原理:
It is
constexpr
if the user-defined constructor would have satisfiedconstexpr
constructor requirements. It is deleted if the corresponding base constructor is deleted or if a defaulted default constructor would be deleted
显然,您不能显式地 constexpr
或 delete
继承的构造函数,因此这些特性只是被继承。访问级别也是如此。