我们如何在函数声明中使用函数参数

How can we use function arguments within a function declaration?

本文关键字:函数 参数 声明 我们      更新时间:2023-10-16

标准N4296::3.3.4/1 [basic.scope.proto]

在函数声明中,或在除 函数定义的声明符 (8.4),参数名称(如果 提供)具有功能原型范围,在末尾终止 最近的封闭函数声明符。

我尝试了以下示例:

1.

template<const int a>
class A{ };
const int a = 4;
A<a> b; // OK
void foo(const int a = 4, A<a>); //non-type template argument is 
                                 //not a constant expression

演示

阿拉伯数字。

void foo(const int a = 4, int b = a); //default argument references parameter 'a'

演示

我们如何使用此示波器的功能?它是为了什么而引入的?

下面是一个人为的例子:

void foo(overly::long_type::which_should_be_a_typedef_anyway a, decltype(a) b); // fine
decltype(a) c; // oops, a not declared

我认为这样做的目的是说以下代码是有效的:

extern int somefunc(int a, char *b, int c);
int somefunc(int, char *, int);
int somefunc(int number, char *bytes, int ipv4_address)
{
    …
}

名称abcextern声明的右括号中失去了意义。 在声明符中,名称很重要,因为int somefunc(int a, char *a, int a);无效,因为在需要不同标识符的情况下使用相同的名称a

名称numberbytesipv4_address在右括号中不会失去它们的意义,因为那是"函数定义的声明符";它们成为函数内变量的名称。

请注意,Stroustrup 明确拒绝将函数声明中的参数名称与函数定义中的参数名称绑定。 在C++的设计与演变中有一节讨论了这个问题。

为了添加到user657267的示例中,尾随返回类型通常依赖于此功能:

template<class A, class F>
auto foo(const A& a, const F& f) -> decltype(f(a));