c++ 14 新特性

1.函数返回值推导

auto func_one(int i) {

return i;

}

 // 模板中也可以这样玩

template<typename T> auto func_one(T t){   

return t;

}

cout << func_one(2) << " " << func_one<double>(5.5) << endl;  //

延伸:

1.函数内如果有多个return语句,它们必须返回相同的类型,否则编译失败

2.如果return语句返回初始化列表,返回值类型推导也会失败

3.如果函数是虚函数,不能使用返回值类型推导

4.返回类型推导可以用在前向声明中,但是在使用它们之前,翻译单元中必须能够得到函数定义

5.返回类型推导可以用在递归函数中,但是递归调用必须以至少一个返回语句作为先导,以便编译器推导出返回类型。

2.lambda参数auto

c++11 lambda参数可以为auto.另外普通函数参数还是不可以为auto

auto func_two = [] (auto a) { return a;};

cout << func_two("hello world!") << " " << func_two("1024") << endl;

输出:hello world! 1024

3.Lambda捕获部分中使用表达式

这意味着我们可以在捕获子句(capture clause)中,也就是[ ]中增加并初始化新的变量,该变量不需要在lambda表达式所处的闭包域中存在

auto ptr = std::make_unique<int>(10); //See below for std::make_unique
auto lambda = [value = std::move(ptr)] {return *value;}

4.更为宽松的constexper

/**
 * C++11: 1. 函数的返回类型以及所有形参的类型都得是字面值类型
 *        2. 函数体中只能由一个return语句
 * C++14: 1. 可以使用局部变量和循环
 *        2. 可以使用多个return
 */
constexpr int factorial_four(int n) { // C++14 和 C++11均可
    return n <= 1 ? 1 : (n * factorial_four(n - 1));
}

// 多返回值与局部变量
constexpr int factorial(int n) { // C++11中不可,C++14中可以
    if(n < 0) return 0;
    int ret = 0;
    // int items[20]; 这样定义是不对的
    for (int i = 0; i < n; ++i) {
        ret += i;
    }
    return ret;
}
输出:
10
120

5.[[deprecated]]标记

C++14中增加了deprecated标记,修饰类、变、函数等,当程序中使用到了被其修饰的代码时,编译时被产生警告,用户提示开发者该标记修饰的内容将来可能会被丢弃,尽量不要使用。
struct [[deprecated]] var_five {
    int item;
};

[[deprecated]] constexpr int func_five(){
    return 200;
}

6.二进制字面量与整形字面量分隔符

C++14引入了二进制字面量,也引入了分隔符,防止看起来眼花哈~

int a = 0b0001'0011'1010;

double b = 3.14'1234'1234'1234;

7.std::make_unique

我们都知道C++11中有std::make_shared,却没有std::make_unique,在C++14已经改善。

 std::unique_ptr<int> ptr = std::make_unique<int>(5);
 cout << *ptr << endl;
 输出:5

8.std::exchange

 std::vector<int> items;
 std::exchange(items, {1,0,2,4});
 for (int x : items) {
     cout << x << " ";
 }
 输出:
 1 0 2 4
template<class T, class U = T>
constexpr T exchange(T& obj, U&& new_value) {
    T old_value = std::move(obj);
    obj = std::forward<U>(new_value);
    return old_value;
}
就是把后面参数的值全部通过move转移到第一个参数上,不过第一个参数的值并不进行转移,

9.std::quoted

C++14引入std::quoted用于给字符串添加双引号。

int main() {
    string str = "hello world";
    cout << str << endl;
    cout << std::quoted(str) << endl;
    return 0;
}

hello world"hello world"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值