是否可以将“自动”关键字用作函数指针声明中使用初始化的返回类型
Is it possible to use the `auto` keyword as a return type in a function pointer declaration with initialization?
以下代码成功编译了 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]
使用
替换auto
和decltype(auto)
类型特性符用于指定占位持有人类型,该类型将在以后从 initializer 。。[...]
auto
或decltype(auto)
应在 dect-specifier-seq 和 em> dect-secifier-seq 中显示为 dect-specifier 随后是一个或多个宣言者,每个声明者应遵循非 initializer 。
这就是说auto
和decltype(auto)
只能与您在声明前面编写的指定器(static
,virtual
等)一起编写,其类型是从 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;
是非法的。
- 为什么我必须以这种方式声明指针?
- 声明指针时更改星号的位置
- 为什么要在初始化SDL之前在SDL中声明指针
- 在C++中声明指针的 2D 数组的方法
- 如何在C 中使用不同数据类型的类模板指针声明指针
- 如何声明指针/引用对模板类成员类型
- C :如何使用thread_local声明指针变量
- 声明指针时的隐式内存分配和初始化
- 了解初始化和声明指针变量时的警告和编译错误
- 在标头中声明指针会导致访问冲突
- 为什么我不能转发声明指针结构?
- 声明指针的动态数组
- 正在声明指针的类型
- C++11 decltype:如何声明指针指向的类型
- C++ 转发声明(指针) - 访问成员
- 为什么我可以在头文件中声明数组,但不能声明指针
- 为什么我需要声明指针而不是对象
- 我们可以声明指针的大小吗?
- 错误 C2143:语法错误:声明指针时'*'之前缺少';'
- 在实现类之前声明指针时出现问题