c++标准14.8.2第3段和第4段的含义是什么?

What is the meaning of 14.8.2 paragraphs 3 and 4 in the C++ Standard?

本文关键字:是什么 4段 3段 标准 c++      更新时间:2023-10-16

我很难理解这个规则,特别是下面粗体的句子(我的重点):

考虑下面代码片段中的注释#2:函数类型是f(int),但tconst是什么意思?

§14.8.2/3 :

替换完成后,将执行8.3.5中描述的函数参数类型调整。[示例:将"void ()(const int, int[5])"的参数类型修改为"void(*)(int,int*)"。[注:函数参数声明中的顶级限定符不影响函数本身类型,但仍然影响函数内函数参数变量的类型。-end note][示例:

]
template <class T> void f(T t);
template <class X> void g(const X x);
template <class Z> void h(Z, Z*);
int main() {
    // #1: function type is f(int), t is non const
    f<int>(1);
    // #2: function type is f(int), t is const
    f<const int>(1);
    // #3: function type is g(int), x is const
    g<int>(1);
    // #4: function type is g(int), x is const
    g<const int>(1);
    // #5: function type is h(int, const int*)
    h<const int>(1,0);

}

-end example]

§14.8.2/4 :

[注: f<int>(1)f<const int>(1)甚至调用不同的函数尽管调用的两个函数都具有相同的函数类型。端注意]

考虑:

template <class T> void f(T t) { t = 5; }

f<int>是格式良好的,但f<const int>不是,因为它试图赋值给const变量。

参见:使用'对于函数参数

如果你有两个函数

void f(int x);
void g(const int x);

则两个函数具有相同的函数类型。此类型表示为void(int), void (*)(int)类型的函数指针可以指向任意一个函数。

这就是当我们说函数参数上的顶级const限定符不影响函数的类型时的意思。

然而,这并不意味着const是没有意义的。在f的定义中,您可以修改x,但在g的定义中,您将无法修改x,因为x的类型是const int