折叠表达式

在 C++11 中对变长参数进行展开比较麻烦,通常采用递归函数的方式进行展开:

  1. void print() { // 递归终止函数
  2. cout << "last" << endl;
  3. }
  4. template <class T, class ...Args>
  5. void print(T head, Args... rest) {
  6. cout << "parameter " << head << endl;
  7. print(rest...); // 递归展开 rest 变长参数
  8. }

C++17 引入折叠表达式来进一步支持变长参数的展开:

  1. // ⼀元左折叠
  2. // 只有一个操作符 「-」,且展开符 ... 位于参数包 args 的左侧,固为一元左折叠
  3. template<typename... Args>
  4. auto sub_val_left(Args&&... args) {
  5. return (... - args);
  6. }
  7. auto t = sub_val_left(2, 3, 4); // ((2 - 3) - 4) = -5;
  8. // 一元右折叠
  9. // 只有一个操作符 「-」,且展开符 ... 位于参数包 args 的右侧,固为一元右折叠
  10. template<typename... Args>
  11. auto sub_val_right(Args&&... args) {
  12. return (args - ...);
  13. }
  14. auto t = sub_val_right(2, 3, 4); // (2 - (3 - 4)) = 3;
  15. // 二元左折叠
  16. // 左右有两个操作符 ,且展开符 ... 位于参数包 args 的左侧,固为二元左折叠
  17. template<typename... Args>
  18. auto sub_one_left(Args&&... args) {
  19. return (1 - ... - args);
  20. }
  21. auto t = sub_one_left(2, 3, 4); // ((1 - 2) - 3) - 4 = -8
  22. // 二元右折叠
  23. // 左右有两个操作符,且展开符 ... 位于参数包 args 的右侧,固为二元右折叠
  24. template<typename... Args>
  25. auto sub_one_right(Args&&... args) {
  26. return (args - ... - 1);
  27. }
  28. auto t = sub_one_right(2, 3, 4); // 2 - (3 - (4 - 1)) = 2

类模板实参推导

C++17 之前类模板无法进行参数推导:

  1. std::pair<int, string> a{ 1, "a"s }; // 需要指明 int, string 类型

C++17 实现了类模板的实参类型推导:

  1. std::pair a{ 1, "a"s }; // C++17,类模板可自行推导实参类型

auto 占位的⾮类型模板形参

  1. template<auto n> struct B { /* ... */ }
  2. B<5> b1; // OK: 非类型模板形参类型为 int
  3. B<'a'> b2; // OK: 非类型模板形参类型为 char
  4. B<2.5> b3; // 错误(C++20前):非类型模板形参类型不能是 double

编译期的 constexpr if 语句

C++17 将 constexpr 这个关键字引入到 if 语句中,允许在代码中声明常量表达式的判断条件

  1. template<typename T>
  2. auto print_info(const T& t) {
  3. if constexpr (std::is_integral<T>::value) {
  4. return t + 1;
  5. } else {
  6. return t + 1.1;
  7. }
  8. }

上述代码将在编译期进行 if 语句的判断,从而在编译期选定其中一条分支。

内联变量(inline 变量)

  1. // student.h
  2. extern int age; // 全局变量
  3. struct Student {
  4. static int age; // 静态成员变量
  5. };
  6. // student.cpp
  7. int age = 18;
  8. int Student::foo = 18;

在 C++17 之前,如果想要使用全局变量或类的静态成员变量,需要在头文件中声明,然后在每个 cpp 文件中定义。
C++17 支持声明内联变量达到相同的效果:

  1. // student.h
  2. inline int age = 18;
  3. struct Student {
  4. static inline int age = 18;
  5. };

结构化绑定

  1. tuple<int, double, string> f() {
  2. return make_tuple(1, 2.3, "456");
  3. }
  4. int main() {
  5. int arr[2] = {1,2};
  6. // 创建 e[2]
  7. // 复制 arr 到 e, 然后 a1 指代 e[0], b1 指代 e[1]
  8. auto [a1, b1] = arr;
  9. cout << a1 << ", " << b1 << endl;
  10. // a2 指代 arr[0], b2 指代 arr[1]
  11. auto& [a2, b2] = arr;
  12. cout << a2 << "," << b2<< endl;
  13. // 结构化绑定 tuple
  14. auto [x, y, z] = f();
  15. cout << x << ", " << y << ", " << z << endl;
  16. return 0;
  17. }

if/switch 语句的变量初始化

if/switch 语句声明并初始化变量,形式为: if (init; condition) 和switch (init; condition)。例子:

  1. for (int i = 0; i < 10; i++) {
  2. // int count = 5; 这条初始化语句直接写在 if 语句中
  3. if (int count = 5; i > count) {
  4. cout << i << endl;
  5. }
  6. }
  7. // char c(getchar()); 这条初始化语句直接写在 switch 语句中
  8. switch (char c(getchar()); c) {
  9. case 'a': left(); break;
  10. case 'd': right(); break;
  11. default: break;
  12. }

u8-char

字符前缀:

  1. u8'c-字符' // UTF-8 字符字面量

简化的嵌套命名空间

  1. namespace X { namespace Y { … }} // 传统
  2. namespace X::Y { … } // C++17 简化命名空间

using 声明语句可以声明多个名称

  1. struct A {
  2. void f(int) {cout << "A::f(int)" << endl;}
  3. };
  4. struct B {
  5. void f(double) {cout << "B::f(double)" << endl;}
  6. };
  7. struct S : A, B {
  8. using A::f, B::f; // C++17
  9. };

将 noexcept 作为类型系统的一部分

与返回类型相似,异常说明成为函数类型的一部分,但不是函数签名的一部分:

  1. // 下面函数是不同类型函数,但拥有相同的函数签名
  2. void g() noexcept(false);
  3. void g() noexcept(true);

新的求值顺序规则

在 C++17 之前,为了满足各个编译器在不同平台上做相应的优化,C++ 对一些求值顺序未做严格规定。最典型的例子如下:

  1. cout << i << i++; // C++17 之前,未定义行为
  2. a[i] = i++; // C++17 之前,未定义行为
  3. f(++i, ++i); // C++17 之前,未定义行为

顺序规则为:a 的求值和所有副作用先序于 b,但同一个字母的顺序不定

强制的复制消除

  1. T Func() {
  2. return T();
  3. }

在传统的复制消除(copy elision)规则下,上述代码将会产生一个临时对象,并将其拷贝给返回值。这个过程可能会被优化掉,也就是拷贝/移动函数根本不会被调用。但程序还是必须提供相应的拷贝函数。
再看如下代码:

  1. T t = Func();

上述代码会将返回值拷贝给 t,这个拷贝操作依然可能被优化掉,但同样的,程序依然需要提供相应的拷贝函数。
从上文可知,在传统的复制消除规则下,下面代码是非法的:

  1. // 传统的复制消除即使优化了拷贝函数的调用
  2. // 但还是会检查是否定义了拷贝函数等
  3. struct T {
  4. T() noexcept = default;
  5. T(const T&) = delete; // C++11 中如果不提供相应的拷贝函数将会导致 return 与 赋值错误
  6. T(T&&) = delete;
  7. };
  8. T Func() {
  9. return T();
  10. }
  11. int main() {
  12. T t = Func();
  13. }

而强制复制消除对于纯右值,将会真正消除上述复制过程,也不会检查是否提供了拷贝/移动函数,所以上述代码在 C++17 中是合法的。
但另一方面,对于具名临时对象,不会进行强制复制消除:

  1. T Func() {
  2. T t = ...;
  3. ...
  4. return t;
  5. }

T还是必须提供拷贝/移动函数

lambda 表达式捕获*this

  1. #include <iostream>
  2. struct Baz {
  3. auto foo() {
  4. // 通过 this 捕获对象,之后在 lambda 即可访问对象的成员变量 s
  5. return[this]{ std::cout << s << std::endl; };
  6. }
  7. std::string s;
  8. };
  9. int main() {
  10. auto f1 = Baz{ "ala" }.foo();
  11. auto f2 = Baz{ "ula" }.foo();
  12. f1();
  13. f2();
  14. }

但上述代码存在一个缺陷:捕获的是当前对象,如果 lambda 表达式对成员变量的访问超出了当前对象的生命周期,就会导致问题。
C++17 提供了 *this捕获当前对象的副本:

  1. auto foo() {
  2. return[*this]{ std::cout << s << std::endl; };
  3. }

constexpr 的 lambda 表达式

C++17 的 lambda 声明为constexpr类型,这样的lambda表达式可以用在其他需要constexpr类型的上下文中。

  1. int y = 32;
  2. auto func = [y]() constexpr {
  3. int x = 10;
  4. return y + x;
  5. };

属性命名空间不必重复

对于由实现定义的行为的非标准属性,可能会带有命名空间:

  1. [[gnu::always_inline, gnu::const, gnu::hot, nodiscard]]
  2. inline int f(); // 声明 f 带四个属性
  3. [[gnu::always_inline, gnu::const, gnu::hot, nodiscard]]
  4. int f(); // 同上,但使用含有四个属性的单个属性说明符

C++11 中上述属性的命名空间需要重复声明,C++17 简化了属性命名空间的定义:

  1. [[using gnu : const, always_inline, hot]] [[nodiscard]]
  2. int f[[gnu::always_inline]](); // 属性可出现于多个说明符中

新属性

  • fallthrough
  • nodiscard
  • maybe_unused

fallthrough

  1. // 以下代码因为没有 case 中没有 break;
  2. // 所以将会发生 case 穿透
  3. // 编译时编译器将会发出警告
  4. int x = 2;
  5. switch (x) {
  6. case 2:
  7. result++;
  8. case 0:
  9. result++;
  10. default:
  11. result++;
  12. }
  13. // 有时候我们需要 case 穿透,如匹配到 2 就一直执行后续的 case
  14. // 此时可以使用属性 [[fallthrough]],使用后,编译器将不会发出警告
  15. switch (x) {
  16. case 2:
  17. result++;
  18. [[fallthrough]]; // Added
  19. case 0:
  20. result++;
  21. [[fallthrough]]; // Added
  22. default:
  23. result++;
  24. }

nodiscard

在开发过程中经常需要对函数返回值进行检查,这一步骤在不少业务场景下是必须的,例如

  1. // 许多人会遗漏对返回值进行检查的步骤
  2. // 导致了很多业务层面潜在的缺陷
  3. if (CallService() != ret) {
  4. // ...
  5. }
  6. // C++17 引入 [[nodiscard]] 属性来「提醒」调用者检查函数的返回值
  7. [[nodiscard]] int CallService() {
  8. return CallServiceRemote();
  9. }
  10. CallService(); // 如果只调用而不检查,编译器将发出警告
  11. if (CallService() != ret) { // pass
  12. // ...
  13. }

maybe_unused

如果我们以-Wunused与-Wunused-parameter编译以下代码,编译器则可能报出警告:

  1. int test(int a, int b, int c) {
  2. int result = a + b;
  3. #ifdef ENABLE_FEATURE_C
  4. result += c;
  5. #endif
  6. return result;
  7. }

原因是编译器认为 c 是未用到的变量,但实际上并非无用。C++17 中可以使用[[maybe_unused]]来抑制针对未使用实体的警告:

  1. int test(int a, int b, [[maybe_unused]] int c) {
  2. int result = a + b;
  3. #ifdef ENABLE_FEATURE_C
  4. result += c;
  5. #endif
  6. return result;
  7. }

__has_include

表明指定名称的头或源文件是否存在:

  1. #if __has_include("has_include.h")
  2. #define NUM 1
  3. #else
  4. #define NUM 0
  5. #endif