0%

Summary about C++17 Part 3

去英國晃了一圈,回來還是寫點東西,免得生疏了

static_assert

沒什麼好說的,就是static_assert改成允許單參數,直接看程式碼

Before C++17

1
static_assert(sizeof(short) == 2, "sizeof(short) == 2")

After C++17

1
static_assert(sizeof(short) == 2)

Inline Variables

對Header-Only library特別有用,不過我不喜歡Header-Only library
原先如果要定義一個變數,要在header宣告,在source code裡面定義
現在可以直接寫在header裡了

Before C++17:

1
2
3
4
5
// foo.h
extern int foo;

// foo.cpp
int foo = 10;

After C++17:

1
2
// foo.h
inline int foo = 10;

constexpr labmda

原先C++14辦不到,C++17允許的能力

1
2
3
4
5
constexpr int Func(int x)
{
auto f = [x]() { return x * x; };
return x + f();
}

不過我還沒想到這東西可以做啥

capture [*this]

原本我還搞不懂capture [this]capture [*this]有什麼不同,自己寫了一個範例之後搞懂了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <iostream>
struct Obj {
Obj() = default;
Obj(const Obj&) { std::cout << "Copy Constructor\n"; }
void f() {}
void g() {}
void h() {}
void func() {
auto lambda1 = [this]() mutable { f(); };
auto lambda2 = [self = *this]() mutable { self.g(); };
auto lambda3 = [*this]() mutable { h(); };
lambda1();
lambda2();
lambda3();
}
};
int main()
{
Obj o;
o.func();
}

capture [*this]相當於上面的[self = *this],會將原有的物件複製一份
[this]不會

More Attributes

C++11引進了Attribute,在C++17增加了更多attributes,如[[fallthrough]]等
就是把GCC/VC的attribute標準化,不多做解釋了

Rest

至於STL的加強就不特別寫了, Guaranteed Copy Elision可能要另外寫
就先寫到這了

Reference

cpp17_in_TTs
C++17