提问人:AlexShane 提问时间:9/26/2023 更新时间:9/26/2023 访问量:70
为什么我可以在 C++11 中使用推导返回类型而不使用尾随返回类型?
why can I use deduced return type without trailing return type in c++11?
问:
我了解到自动推断的返回类型是 c++14 的一个特性,如下所示
template <typename Func, typename ...Args>
auto post(Func func, Args... args);
有人告诉我,如果我想在 C++11 中使用它,我必须使用尾随返回类型,如下所示
template <typename Func, typename ...Args>
auto post(Func func, Args... args) -> decltype(xxxxxx);
但实际上我可以在我的 PC 中成功编译 no-trailing-return-type 的,编译器不会报告错误,它只是报告这样的警告:std=c++11
warning: 'post' function uses 'auto' type specifier without trailing return type [enabled by default]
尽管有此警告信息,但该程序仍按照我的设计运行良好。为什么不是错误消息?
我想知道为什么编译器允许我这样做,因为这是 c++14 的功能。我注意到警告信息中有一个。这是否意味着编译器强制自己接受这种语法?顺便说一句,我的编译器是gcc 4.8.5std=c++11
[enabled by default]
我用(使用 gcc 4.8.5)编译它std=c++11
template <typename Func, typename ...Args>
auto post(Func func, Args... args);
我认为它应该报告一个错误,但它确实报告了警告,然后允许我这样做:
warning: 'post' function uses 'auto' type specifier without trailing return type [enabled by default]
答:
1赞
Caleth
9/26/2023
#1
因为编译器具有 C++14 功能,所以要在 C++14 模式下进行编译。在 C++11 模式下,默认情况下,它启用它作为语言的非标准扩展。该选项会关闭这些扩展,这将使它成为错误。-pedantic-errors
评论
0赞
AlexShane
9/26/2023
谢谢你的回答!它完全解决了我的问题。
评论