是否可以将“自动”关键字用作函数指针声明中使用初始化的返回类型

Is it possible to use the `auto` keyword as a return type in a function pointer declaration with initialization?

本文关键字:声明 指针 初始化 返回类型 函数 自动 是否 关键字      更新时间:2023-10-16

以下代码成功编译了 clang 3.8.0 g 7.2.0 (编译标志为 -std=c++14 -O0 -Wall -Wextra -Werror -pedantic-errors):

#include <iostream>

int foo_int(int)
{
    std::cout << "int foo(int)" << std::endl;
    return 0;
}
void foo_void(int)
{
    std::cout << "void foo(int)" << std::endl;
}
auto foo_auto_int(int)
{
    std::cout << "auto foo(int), auto == int" << std::endl;
    return 0;
}
auto foo_auto_void(int)
{
    std::cout << "auto foo(int), auto == void" << std::endl;
    return void();
}

int main()
{
    auto (*fi)(int) = foo_int;
    auto (*fv)(int) = foo_void;
    auto (*fai)(int) = foo_auto_int;
    auto (*fav)(int) = foo_auto_void;
    (void)fi(0);
    fv(0);
    (void)fai(0);
    fav(0);
}

它是有效的C 代码吗?

请注意,在同一情况下,decltype(auto)均被 clang g 拒绝。

编译器的行为正确。

来自[dcl.spec.auto]

使用autodecltype(auto)类型特性符用于指定占位持有人类型,该类型将在以后从 initializer 。。

替换

[...]

autodecltype(auto)应在 dect-specifier-seq em> dect-secifier-seq 中显示为 dect-specifier 随后是一个或多个宣言者,每个声明者应遵循非 initializer

这就是说autodecltype(auto)只能与您在声明前面编写的指定器(staticvirtual等)一起编写,其类型是从 and em>的紧随其后的 em>中推导的类型>初始化器

auto

的情况

auto (*fi)(int) = foo_int;的情况下,声明器(*fi)(int),是形式

( ptr-operator declarator-id ) ( parameter-declaration-clause )

因此,只要扣除成功, auto (*fi)(int) = foo_int;是有效的。同样对于其他几个。

decltype(auto)

的情况

来自[dcl.spec.auto.deduct],给定 T包含占位符类型

的类型

如果占位符是 decltype(auto) 类型特征,则T应为占位符。

这意味着添加其他任何内容是非法的

int i;
decltype(auto)* p = &i;  // error, declared type is not plain decltype(auto)

因此decltype(auto) (*fi)(int) = foo_int;是非法的。