我最近了解到构造函数没有名称。我还知道函数有一个称为函数类型的类型。例如,
void func(int)
{
}
在上面的代码片段中,func
具有函数类型 void (int)
。
现在,既然构造函数是特殊的成员函数,那么它们是否也有像上面所示的类型呢?例如,假设我们有:
struct Name
{
Name(int)
{
}
};
上面显示的构造函数是否也像普通函数或普通成员函数一样具有函数类型?如果是,那么我们如何找到该类型呢?是否允许在构造函数上使用 decltype 来查找其类型,就像对普通函数所做的那样?
I recently learnt that constructors do not have names. I am also aware that a function has a type called a function type. For example,
void func(int)
{
}
In the above snippet, func
has the function type void (int)
.
Now, since constructors are special member functions, do they also have a type like the one shown above? For example say we have:
struct Name
{
Name(int)
{
}
};
Does the constructor shown above also have a function type just like ordinary functions or ordinary member functions? If yes, then how can we find that type? Is it permitted to use decltype
on constructors to find their type, like one would do for ordinary functions?
发布评论
评论(2)
它是否允许 。主要是因为没有办法命名构造函数。一个常见的错误表明是
name(0)
或new Name(0)
,调用构造函数的表达式。但事实并非如此,例如func(0)
中的情况。我们从来没有直接调用构造函数,而是始终是由需要新对象出现的语言构造而间接的。因为我们无法命名它们,所以我们无法使用
exltype
之类的内省机制来检查它们。因此,该标准没有为构造函数指定“类型”,因为严格符合标准的程序无法检查该类型。构造函数也不能具有签名(标准定义),因为根据定义,构造函数包括函数名称(如提到的构造函数是无名的)。
It's not permitted. Primarily because there is no way to name a constructor. A common misnomer is that an expression like
Name(0)
ornew Name(0)
, calls the constructor. But that isn't the case like infunc(0)
. A constructor is never called by us directly, but rather always indirectly by the language construct that requires a new object to come into being.Because we cannot name them, we cannot use introspection mechanisms like
decltype
to examine them. Therefore the standard doesn't specify a "type" for constructors, since there is no way for a strictly standard compliant program to examine said type.A constructor also cannot possess a signature (as defined by the standard), since that by definition includes the function name (and constructors are, as mentioned, nameless).
这是 CWG2476,其状态为
DRWP
(在 C++26 工作草案中接受的意思)这也使得构造函数具有类型。注意已发布 c++23不允许构造函数具有类型:C++23
这里
T D
中的T
不允许为空,这意味着构造函数在 C++ 中没有类型23 已发布。来自 dcl.fct:
这里注意
T
在CWG2476 表示构造函数在 C++23 中没有类型。CWG2476
在 C++26 的工作草案中,
T
可以为空,这意味着现在构造函数确实有一个类型。请注意,在上面的 CWG 中添加了对“T 可能为空”的强调,这意味着构造函数
Name::Name(int)
确实有一个类型。This is CWG2476 whose status is
DRWP
(meaning accepted in C++26 working draft) which also makes constructors have a type. Note as published c++23 did not allow constructors to have a type:C++23
Here
T
inT D
is not allowed to be empty meaning a constructor doesn't have a type in C++23 as published.From dcl.fct:
Note here
T
was not allowed to be empty before CWG2476 meaning a constructor function doesn't have a type in C++23.CWG2476
In the working draft of C++26,
T
can be empty, meaning now constructors do have a type.Note the emphasis on T may be empty added in the above CWG which means the constructor
Name::Name(int)
does have a type.