c++标准14取消decltype推算函数返回类型

来源:互联网 发布:手机直播系统源码 编辑:程序博客网 时间:2024/06/15 06:49

Table of Contents

  • 1. c++11之前不支持auto关键字
  • 2. c++11支持auto关键字
    • 2.1. 但是不能自动推断函数返回类型
    • 2.2. 使用-> decltype来声明返回类型
  • 3. c++14让事情又回到简单
  • 4. 我们该使用哪个c++版本

1 c++11之前不支持auto关键字

下面的auto关键字在c++11之前是不支持的

auto add(int a, int b) {   int i = a + b;   return i;}int main(int argc,char ** argv) {  try {     std::cout << add(1,2) << std::endl;   } catch(std::exception const &e) {     std::cerr << e.what() << std::endl;  }}

编译器clang++ 3.6 会如下报错:

../src/main.cc:13:1: warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]auto add(int a, int b) {^../src/main.cc:13:1: error: 'auto' not allowed in function return typeauto add(int a, int b) {^~~~

2 c++11支持auto关键字

2.1 但是不能自动推断函数返回类型

还是上面的例子代码,这次编译加上-std=c++11

../src/main.cc:13:1: error: 'auto' return without trailing return type; deduced return types are a C++14 extensionauto add(int a, int b) {^1 error generated.

这里clang++报错, 说auto后面没有跟上返回类型的说明, 或者使用c++14标准提供的deduced return types.

2.2 使用-> decltype来声明返回类型

先来看看C++11的推荐做法, 在函数后面加上怪怪的语法

auto add(int a, int b) -> decltype(a + b) {

编译通过.

3 c++14让事情又回到简单

-> decltype(a+ b) 这个语法让人一下感觉不像c++了. 不过14标准作为11标准的快速跟进, 又把事情拉回去. -> decltype变成了短命的过渡方案. 现在可以完全抛弃不用了. 在编译选项中添加-std=c++14后, 下面的代码就通过了

auto add(int a, int b) {   int i = a + b;   return i;}

4 我们该使用哪个c++版本

由于c++14标准已经发布, 而主要编译器都已经支持, 因此现在不是再谈c++11的时候, 而是应该直接使用c++14标准. 这里是clang编译器对c++标准的支持文档 同时,这里有我的例子工程: git@gitlab.com:newlisp/cppwizard.git, 采用我自己的newlisp builder对c++代码进行编译 只需要修改debug_config.lsp文件的编译选项即可.

(set 'compile-options "-g -std=c++14")

更新的c++ 17 或者 1z还在制定标准过程中, 当前不建议使用.

Author: dean

Created: 2015-12-27 日 10:23

Validate

0 0
原创粉丝点击