如何在自己的定义中缩写 class 名称?
How to abbreviate class name inside its own definition?
如何在 class 的定义中为冗长的 class 名称创建别名?我不希望它可以在 class 定义之外访问。我无法使用 typedef
或 using
.
我的例子是 class 模板。
template<typename T>
class detailed_class_name{
typedef detailed_class_name<T> foo; // either one
using foo = detailed_class_name<T>; // of these
public:
foo(); // Error: ISO C++ forbids declaration of 'foo' with no type.
};
有什么想法吗?
你不能。构造函数的 id-expression,即 class 定义中构造函数的名称是根据 [class.ctor]p1(强调我的):
- in a member-declaration that belongs to the member-specification of a class but is not a friend declaration, the id-expression is the injected-class-name of the immediately-enclosing class;
什么是注入的-class-名称?根据[class]p2
A class-name is inserted into the scope in which it is declared immediately after the class-name is seen. The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name. [...]
因此注入的-class-name 是 class 本身的名称,不能是别名。
[class.ctor]p1中的这句话进一步强化了这一点:
The class-name shall not be a typedef-name.
如果您因为名称太复杂而不想编写构造函数,请考虑重命名 class。
如何在 class 的定义中为冗长的 class 名称创建别名?我不希望它可以在 class 定义之外访问。我无法使用 typedef
或 using
.
我的例子是 class 模板。
template<typename T>
class detailed_class_name{
typedef detailed_class_name<T> foo; // either one
using foo = detailed_class_name<T>; // of these
public:
foo(); // Error: ISO C++ forbids declaration of 'foo' with no type.
};
有什么想法吗?
你不能。构造函数的 id-expression,即 class 定义中构造函数的名称是根据 [class.ctor]p1(强调我的):
- in a member-declaration that belongs to the member-specification of a class but is not a friend declaration, the id-expression is the injected-class-name of the immediately-enclosing class;
什么是注入的-class-名称?根据[class]p2
A class-name is inserted into the scope in which it is declared immediately after the class-name is seen. The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name. [...]
因此注入的-class-name 是 class 本身的名称,不能是别名。
[class.ctor]p1中的这句话进一步强化了这一点:
The class-name shall not be a typedef-name.
如果您因为名称太复杂而不想编写构造函数,请考虑重命名 class。