为什么不能推导返回类型的main? [英] Why can the return type of main not be deduced?

查看:144
本文介绍了为什么不能推导返回类型的main?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如预期,C ++ 11中的以下语句失败,因为该语言没有对bog标准函数的返回类型扣除:

  auto main()
{
return 0;
}

但是,C ++ 14不支持,所以我不能解释下面的错误在GCC trunk,clang 3.8和Visual Studio 2015中的等效结果):

 错误:'main'必须返回'int'

标准中有一个段落,我没有看到,禁止返回类型扣除 main



(对于有价值的东西,我从来不会这么做。 int main {@ } 已解决方法 /open-std.org/JTC1/SC22/WG21/docs/papers/2016/n4594.pdf\"> C ++ 17草稿§3.6.1/ 2:


...并且它应该有一个声明的返回类型 int ,...


所以是的,我会说禁止使用扣除。






几乎与最后一个C ++ 14中的完全相同的措辞草案(与C ++ 17草案相同的部分):


它的声明返回类型类型 int ,...







在阅读评论和其他答案后,只是个人的反思,在这背后的可能的推理。不允许推理返回类型的扣除是(我认为),因为然后返回类型是不知道的编译器,直到它看到一个 return 语句。其他类型(可隐式转换为 int )可能被返回,这将导致推断的类型错误也并不罕见。声明返回类型前面(通过正常的老式方式或通过使用结尾返回类型)将在声明函数时设置类型,并且可以由编译器检查,然后正确。 p>

对于允许类型别名,它们只是类型的别名。所以允许例如

  typedef int my_type; 
my_type main(){...}

>

  int main(){...} 


As expected, the following fails in C++11 because that language does not have return type deduction for bog standard functions:

auto main()
{
   return 0;
}

However, C++14 does, so I cannot explain the following error (with equivalent outcomes in GCC trunk, clang 3.8 and Visual Studio 2015):

error: 'main' must return 'int'

Is there a passage in the standard that I'm not seeing, forbidding return type deduction for main? Or are both compilers non-compliant?

(For what it's worth, I'd never actually do this. int main() for the win…)

解决方案

Reading the C++17 draft §3.6.1/2:

... and it shall have a declared return type of type int, ...

So yes I would say it's forbidden to use deduction.


Almost the exact same wording in the last C++14 draft (same section as the C++17 draft):

It shall have a declared return type of type int, ...


Just a personal reflection on the possible reasoning behind this, after reading comments and other answers. The reasoning return-type deduction is not allowed is (I think) because then the return type isn't known by the compiler until it sees a return statement. It's also not uncommon that other types (that are implicitly convertible to int) might be returned which would make the deduced type wrong. Declaring the return type up-front (either by the normal old-fashioned way, or by using trailing return type) will set the type when the function is declared, and can be checked by the compiler then and there to be correct.

As for allowing type-aliases, they are just aliases of a type. So allowing e.g.

typedef int my_type;
my_type main() { ... }

is really no different from

int main() { ... }

这篇关于为什么不能推导返回类型的main?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆