C++17新增特性
收录于 Cplusplus 浏览量
cplusplus语言特性
If Statements with initializer
带初始化的If语句
std::map<std::string, int> map;
map["a"] = 1;
map["b"] = 2;
if (auto ret = map.begin(); ret != map.end()) {
std::cout << ret->first << ": " << ret->second;
}
Constexpr if
在该语句中,条件的值必须是可以按语境转换到bool类型的转换常量表达式。若其值为true,则舍弃false分支语句,否则舍弃true语句。
template<typename T>
void ConstexprIf(T value) {
if constexpr (std::is_integral_v<T>) {
std::cout << "is integral" << std::endl;
} else {
static_assert(false, "T必须是整型");
}
}
属性说明符
[[fallthrough]]
指示出从前一标号直落是有意义的,而发生直落给出告警的编译器不应该诊断它。
switch (device.status()) {
case sleep:
device.wake();
[[fallthrough]];
case ready:
device.run();
break;
case bad:
handle_error();
break;
}
之前编译器会通告没有break的告警,在C++17后使用fallthrough属性就可以消除这个警告了。
[[maybe_unused]]
可以用来消除未使用的函数或变量编译器发出的告警。
[[maybe_unused]] bool unusedVariable = true;
[[maybe_unused]] uint32_t UnusedFunction()
{
return 0;
}
[[nodiscard]]
如果你的某个函数返回值特别重要,希望使用者不要忽略,可以添加这个属性,在编译的时候如果函数使用者没有使用返回值将会产生一个告警;
[[nodiscard]] bool function()
{
return true;
}
[[deprecated]]
提示允许使用声明有此属性的名称或实体,但因为一些原因不被鼓励使用,一般用在即将废弃的函数,但是还有老用户使用了这个函数;
[[deprecated("test deprecated")]] bool function()
{
return true;
}
[[noreturn]]
用来告知函数没有返回值
[[noreturn]] void function() {
}
inline变量
inline 变量解决全局变量在头文件中定义之后多处使用产生符号定义错误。
// 以前会报错
// test.h
int test = 10;
// test1.cpp
void fun1()
{
test = 20;
}
// test2.cpp
void fun2()
{
test = 30;
}
// 重定义错误解决办法
// test.h
extern int test;
// test.cpp
int test = 10;
C++17之后引入的inline变量使得全局变量可以直接在头文件中声明定义。
// test.h
inline int test = 10;
string_view
string_view相对于string来说就是一个只读的string,string_view的赋值操作的空间成本和时间成本远远胜于string,string_view的赋值特别像一个指针的赋值,一般来说在以情况使用string_view比较合适。
// 常量string
const string str = "hello world!";
// string_view比较合适
constexpr string_view str = "hello world!";
// 函数参数
void fun(const string &str)
{
}
// string_view
void fun(const string_view &str)
{
}
any
any是一个可以用于任何类型的单个值的类型安全容器。
std::any Int = 10;
std::any Double = 1.234;
std::any String = std::string_view("hello world!");
std::vector<std::any> anys{Int, Double, String};
std::cout << std::any_cast<int>(Int) << std::endl;
std::cout << std::any_cast<double>(Double) << std::endl;
std::cout << std::any_cast<std::string_view>(String) << std::endl;
std::any a = 1;
if (a.has_value()) {
std::cout << a.type().name() << std::endl;
}
a.reset();
if (!a.has_value()) {
std::cout << "no value" << std::endl;
}
optional
在返回值是string或者int等出现错误之后非常隐式的表达的地方,使用std::optional就可以帮你解决这一问题;另外就是当对外暴漏了一个结构体,但是里面有些参数是可选项,那optional就派上用场了。
// 1
[[nodiscard]] std::optional<int> TestOptional1()
{
if (ok) {
return 100;
} else {
return std::nullopt;
}
}
[[nodiscard]] std::optional<string> TestOptional2()
{
if (ok) {
return "hello world!";
} else {
return std::nullopt;
}
}
// optional
auto res = TestOptional1();
if (res.has_value()) {
// success
} else {
// fail
}
auto ret = TestOptional2().value_or("");
// 2
struct MyStruct {
std::optional<int> width;
std::optional<int> height;
int fps{30};
};
void DoSomething(const MyStruct &myStruct)
{
if (myStruct.width.has_value()) {
// ...
}
if (myStruct.height.has_value()) {
// ...
}
}
variant
variant是一个类型安全的联合体,variant的一个实例在任意时刻要么保有其一个可选类型之一的值,要么在错误的情况下无值。variant不容许保有引用,数组,或类型void,空variant可以使用std::variant<std::monostate>。
struct SystemProxyConfig {
bool isFile;
};
struct CustomProxyConfig {
bool isFile;
std::string pathOrContent;
};
std::variant<SystemProxyConfig, CustomProxyConfig> config;
config = SystemProxyConfig{false};
if (std::get_if<CustomProxyConfig>(&config)) {
// 成功
CustomProxyConfig customCfg = std::get<CustomProxyConfig>(config);
} else {
// 失败
SystemProxyConfig systemCfg = std::get<SystemProxyConfig>(config);
}
execution
execution为c++stl算法库提供了一种算法的执行策略设置,目前支持的策略:
sequenced_policy(顺序执行策略)parallel_policy(并行执行策略)parallel_unsequenced_policy(并行及无序执行策略)unsequenced_policy(无序执行策略)
std::vector<int> testExecution{1,2,3,4,58,23,56,78,55,66,77,9,1,0,45,1111,45,13,57};
auto it1 = std::find(std::execution::seq, testExecution.begin(), testExecution.end(), 5);
auto it2 = std::find(std::execution::par, testExecution.begin(), testExecution.end(), 5);
auto it3 = std::find(std::execution::par_unseq, testExecution.begin(), testExecution.end(), 5);
结构化绑定
结构化绑定可以把元组、结构体、数组等”整体”一次性拆到多个具名变量里,配合 if/for 的初始化语法能让代码更直观。
std::map<std::string, int> ages = std::map<std::string, int>({
std::make_pair("Tom", 18),
std::make_pair("Jerry", 20)
});
// 遍历 map 时不必再写 .first/.second
for (const auto &[name, age] : ages) {
std::cout << name << ": " << age << std::endl;
}
// 也可以绑定结构体
struct Point {
int x;
int y;
};
Point p{1, 2};
auto [x, y] = p;
// 返回多个值也不用再构造 out 参数
std::tuple<int, bool> Divide(int a, int b) {
if (b != 0) {
return std::make_tuple(a / b, true);
}
return std::make_tuple(0, false);
}
auto [quot, ok] = Divide(10, 3);
折叠表达式
C++17 之前在变参模板里展开参数包需要写递归函数或 std::initializer_list 的 hack;折叠表达式允许直接对参数包应用二元运算符,写法干净很多。
template<typename... Args>
auto Sum(Args... args)
{
return (args + ...); // 一元右折叠: a1 + (a2 + (a3 + ...))
}
template<typename... Args>
auto Sum2(Args... args)
{
return (args + ... + 0); // 带初始值: ((a1 + a2) + 0),空包也能编译
}
template<typename... Args>
void PrintAll(Args&&... args)
{
((std::cout << args << " "), ...); // 逗号折叠,依次打印所有参数
}
类模板实参推导(CTAD)
以前使用类模板总要显式写出模板实参;C++17 之后编译器可以根据构造函数或推导指引自动推导,std::pair、std::lock_guard、容器等的用法都顺手了。
std::mutex m;
// 以前: std::lock_guard<std::mutex> lg(m);
std::lock_guard lg(m); // 推导出 std::lock_guard<std::mutex>
std::vector v{1, 2, 3}; // 推导出 std::vector<int>
std::pair p{1, 1.23}; // 推导出 std::pair<int, double>
// 自定义类模板可以用"推导指引"辅助推导
template<typename T>
struct Wrapper {
T value;
Wrapper(T v) : value(v) {}
};
Wrapper(const char *) -> Wrapper<std::string>;
Wrapper w{"hello"}; // w 的类型是 Wrapper<std::string>
constexpr lambda
C++17 起 lambda 表达式在满足条件时隐式为 constexpr,也可以显式声明,用于编译期计算。
constexpr auto square = [](int n) constexpr {
return n * n;
};
static_assert(square(6) == 36, "");
scoped_lock 与 shared_mutex
std::scoped_lock 是”一次锁住多个互斥量”的组合锁,内部使用死锁回避算法,取代了 std::lock 的繁琐写法;同为 C++17 新增的 std::shared_mutex(读写锁)则允许读多写少的场景下多个读者并行。
std::mutex m1, m2;
std::shared_mutex rw;
{
std::scoped_lock lock(m1, m2); // 同时锁两把锁,不会死锁
// ...
}
{
std::shared_lock rl(rw); // 读锁:多读者可并行
// ...
}
{
std::unique_lock wl(rw); // 写锁:独占
// ...
}
std::filesystem
std::filesystem 终于把”目录遍历、路径操作、文件属性”这些系统相关操作标准化,不用再为 Windows/Linux 各写一套。
namespace fs = std::filesystem;
fs::path dir = "E:/workspace";
for (const auto &entry : fs::directory_iterator(dir)) {
std::cout << entry.path() << std::endl;
}
std::cout << fs::file_size(dir / "a.txt") << std::endl;
std::cout << fs::exists(dir) << std::endl;
fs::create_directory("E:/tmp_dir");
fs::rename("E:/tmp_dir", "E:/tmp_dir_renamed");
std::charconv
std::to_chars / std::from_chars 提供了不涉及流和区域设置的快速整数/浮点转换,性能比 std::stringstream 好一个量级,且分配一次内存都不需要。
char buf[32];
// 整数转字符串:不依赖流,最快路径
auto [ptr, ec] = std::to_chars(buf, buf + 32, 1024);
if (ec == std::errc()) {
std::cout << std::string_view(buf, ptr - buf) << std::endl; // 1024
}
// 字符串转整数
int val = 0;
auto [p, e] = std::from_chars(buf, buf + 4, val);
其他
template<auto N>允许非类型模板参数按auto推导。- lambda 中可以
[*this]按值捕获整个对象。 std::byte作为字节语义的独立类型;std::clamp、std::sample等新算法。std::string_view(上文)与 CTAD 组合后,传参更高效。