(C++进阶)C++20

发布于:2024-10-12 ⋅ 阅读:(7) ⋅ 点赞:(0)

目录

一、概述

二、新特性

1. 模块(Modules)功能

2. 概念(Concepts)功能

3. 范围(Ranges)功能

4. 协程(Coroutines)功能

5. 三路比较运算符(Spaceship Operator)功能

6. std::format功能

7. 位操作增强

8. 空指针比较

一、概述

C++20作为C++语言的一个重要更新,引入了许多提升编程效率和代码质量的新特性。

二、新特性

1. 模块(Modules)功能

模块旨在替换传统的头文件 #include模型,以减少编译时间和改善依赖管理。

代码示例:

// my_module.module
export module my_module;
export void greet()
{
    std::cout << "Hello from the module!" << std::endl;
}

// main.cpp
import my_module;
int main() 
{
    greet();
    return 0;
}

2. 概念(Concepts)功能

概念允许在编译时精确指定模板参数需满足的条件,增强编译时错误信息和泛型编程的清晰度。

代码示例:

#include <concepts>
template <typename T>
concept Integral = std::is_integral_v<T>;

template<Integral T>
T abs(T x) 
{
    return x >= 0 ? x : -x;
}

int main() 
{
    static_assert(abs(42) == 42);
    static_assert(abs(-42) == 42);
    // static_assert(abs(42.0) == 42.0); // 错误,double不满足Integral概念
    return 0;
}

3. 范围(Ranges)功能

范围库扩展了标准库中的算法,支持更简洁、更灵活的序列操作。

代码示例:

#include <range/v3/all.hpp>
#include <iostream>
int main() 
{
    std::vector<int> vec = {1, 2, 3, 4, 5, 6};
    auto even = vec | ranges::view::filter([](int x) { return x % 2 == 0; });
    for (int val : even) 
    {
        std::cout << val << " ";
    }
    return 0;
}

4. 协程(Coroutines)功能

正式支持协程,使得编写异步代码更为直观。

代码示例(简化的生成器示例):

#include <coroutine>
#include <iostream>

struct Generator 
{
    struct promise_type;
    using handle_t = std::coroutine_handle<promise_type>;

    Generator(handle_t h) : coro(h) {}
    ~Generator() { if (coro) coro.destroy(); }
    int next() 
    {
        coro.resume();
        return coro.promise().current_value;
    }

    private:
    handle_t coro;
};

struct Generator::promise_type 
{
    int current_value{0};
    Generator get_return_object() { return Generator{handle_t::from_promise(*this)}; }
    std::suspend_always initial_suspend() { return {}; }
    std::suspend_always final_suspend() noexcept { return {}; }
    void return_value(int value) { current_value = value; }
    void unhandled_exception() { std::terminate(); }
};

Generator count_up_to(int limit) 
{
    for (int i = 1; i <= limit; ++i) 
    {
        co_yield i;
    }
}

int main() 
{
    for (int val : count_up_to(5)) 
    {
        std::cout << val << " ";
    }
    return 0;
}

5. 三路比较运算符(Spaceship Operator)功能

引入了<=>运算符,用于实现综合比较(小于、等于、大于)。

代码示例:

#include <compare>
struct Point 
{
    int x, y;
    auto operator<=>(const Point&) const = default;
};

int main() 
{
    Point p1{1, 2}, p2{1, 2};
    if (p1 == p2) std::cout << "Equal" << std::endl;
    return 0;
}

6. std::format功能

std::format 是 C++20 引入的标准库函数,它为字符串格式化提供了统一且强大的接口,类似于 Python 中的 str.format 或 C 的 printf 函数,但更加安全和灵活。

代码示例:

#include <format>
#include <iostream>

int main() 
{
    auto str = std::format("The answer is {}.", 42);
    std::cout << str << std::endl; // 输出: The answer is 42.
    return 0;
}

7. 位操作增强

C++20 对位操作进行了增强,引入了几个新函数来提高位操作的便利性和表达能力:①std::bit_cast<>:

允许在 trivially_copyable 类型之间直接转换比特模式。

②std::has_single_bit():

检查给定的整数是否是 2 的幂。

③std::countl_zero() 和 std::countr_zero():分别从左和从右开始计算连续的零位数量。④std::popcount():

计算一个整数中设置为 1 的位数。

代码示例(使用 std::has_single_bit 和 std::countl_zero):

#include <bit>
#include <iostream>

int main() 
{
    unsigned int num = 0b100000;
    std::cout << "Is power of 2? " << std::boolalpha << std::has_single_bit(num) << std::endl;
    std::cout << "Leading zeros: " << std::countl_zero(num) << std::endl;
    return 0;
}

8. 空指针比较

C++20 引入了新的空指针常量 nullptr 与整数类型的比较操作,明确禁止了这种比较,以防止潜在的逻辑错误。 以前,比较 nullptr 和整数在某些实现下是允许的,但现在这样的比较会引发编译错误,确保了代码的清晰和安全。

代码示例(演示非法比较):

void checkPointer(int* ptr) 
{
    // if (ptr == 0) 
    // {    
            // 在C++20中,这种比较会被认为是错误的
            // std::cout << "ptr is null" << std::endl;
    // }
    if (!ptr) 
    { // 推荐的检查空指针方式
        std::cout << "ptr is null" << std::endl;
    }
}

int main() 
{
    checkPointer(nullptr);
    return 0;
}