以自动返回类型作为参数的函数

Function with auto return type as parameter

本文关键字:参数 函数 返回类型      更新时间:2023-10-16
这是

不允许的,因为它包含auto

void f(auto fp())
{
}
// error: 'auto' not allowed in function prototype

我们可以显式地使其成为函数指针并得到相同的错误:

void f(auto (*fp))
{
}

现在,如果我们给它一个尾随返回类型:

void f(auto fp() -> int)
{
}

现在没事了。这是合法的,编译器错误还是疏忽?

有趣的是,它不允许我将auto函数指针作为参数。

// OK
void f(auto f(auto () -> int) -> int)
{
}
// Complain
void f(auto f(auto (*fp) -> int) -> int)
{
}
用于

自动类型扣除的auto不同于用于指定尾随返回类型的auto

C++11 中的函数参数不支持自动类型推断auto

但是,C++14 及更高版本支持 lambda 函数参数的auto。实质上,这会在 lambda 类型中创建模板化operator()


您的示例

void f( auto fp() -> int )
{}

使用尾随返回类型语法指定 C++03 语法函数

void f( int fp() )
{}

由于用作形式参数类型的函数类型的衰减,等效

void f( int (*fp)() )
{}

使用函数指针参数。