C++14 新特性

一、函数返回类型推导增强

  1. 普通函数返回类型推导
// C++11 需要尾置返回类型
auto add(int a, int b) -> int { return a + b; }

// C++14 可以直接推导
auto add(int a, int b) { return a + b; }
  1. decltype(auto) 返回类型
int& get_ref(int& x) { return x; }

// C++11 方式
auto get_ref11(int& x) -> int& { return x; }

// C++14 更简洁
decltype(auto) get_ref14(int& x) { return x; }

二、泛型 Lambda 表达式

  1. 参数类型使用 auto
// C++11 Lambda 必须指定参数类型
auto lambda11 = [](int x, int y) { return x + y; };

// C++14 泛型 Lambda
auto lambda14 = [](auto x, auto y) { return x + y; };

// 使用
int i = lambda14(3, 4); // int 版本
double d = lambda14(3.5, 4.5); // double 版本
  1. Lambda 捕获表达式
int x = 10;

// C++11 只能捕获变量
auto lambda11 = [x]() { return x; };

// C++14 可以捕获表达式结果
auto lambda14 = [value = x * 2]() { return value; };

三、变量模板

// C++11 只有类模板和函数模板
template<typename T>
constexpr T pi = T(3.1415926535897932385);

// 使用
float f = pi<float>;
double d = pi<double>;

四、二进制字面量

int x = 0b101010; // 二进制表示,等于十进制的42

五、数字分隔符

int million = 1'000'000;
double pi = 3.141'592'653'589'793;

六、[[deprecated]] 属性

[[deprecated("Use new_func() instead")]]
void old_func() {}

// 使用时编译器会发出警告
old_func();

七、constexpr 函数增强

  1. 允许局部变量和循环
constexpr int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}

constexpr int fact5 = factorial(5); // 120
  1. 允许 if 语句
constexpr bool is_even(int x) {
if (x % 2 == 0) {
return true;
} else {
return false;
}
}

八、std::make_unique

#include <memory>

// C++11 只有 std::make_shared
auto sp = std::make_shared<int>(42);

// C++14 新增 std::make_unique
auto up = std::make_unique<int>(42);

九、std::integer_sequence

#include <utility>

template<typename T, T... Ints>
void print_sequence(std::integer_sequence<T, Ints...>) {
((std::cout << Ints << ' '), ...); // C++17 折叠表达式
}

// 使用
print_sequence(std::integer_sequence<int, 1, 2, 3>{}); // 输出: 1 2 3

十、std::exchange

#include <utility>

int x = 10;
int old = std::exchange(x, 20); // old=10, x=20

十一、std::quoted

#include <iomanip>
#include <string>

std::string s = "Hello";
std::cout << std::quoted(s); // 输出: "Hello"

十二、std::shared_timed_mutex

#include <shared_mutex>

std::shared_timed_mutex mtx;

// 读锁(共享锁)
{
std::shared_lock<std::shared_timed_mutex> lock(mtx);
// 读取操作
}

// 写锁(独占锁)
{
std::unique_lock<std::shared_timed_mutex> lock(mtx);
// 写入操作
}

十三、std::cbegin/std::cend

#include <vector>
#include <iterator>

std::vector<int> v = {1, 2, 3};

// C++11 方式
auto it11 = v.cbegin();

// C++14 更通用的方式
auto it14 = std::cbegin(v);

十四、聚合成员初始化

struct Point {
    int x, y;
};

// C++11 需要构造函数或初始化列表
Point p1{1, 2};

// C++14 可以直接初始化
Point p2{1}; // p2.x=1, p2.y=0

十五、std::tuple 元素访问

#include <tuple>

auto t = std::make_tuple(1, 2.5, "hello");

// C++11 只能通过 std::get<index>
int x = std::get<0>(t);

// C++14 可以通过类型获取
double d = std::get<double>(t); // 获取 double 类型的元素
滚动至顶部