綜合 Toronto, Rapperswil, San Diego, Kona meeting 的結果, Modules, Ranges, Coroutines, Concepts, Contracts 都已經併入 C++20


Modules

Merging Modules

告別頭文件,更快的編譯速度,更好的build cache/可能的包管理。主要問題在於module mapping需要編譯器和build system的協作,這一部分將來還有許多變數。

長話短說,直接上例子:

舊代碼怎麼轉換成模塊

include

這種方式include的header還會走舊的preprocessor一套。

包裝代碼:

module;
#include "some-header.h" //原有的老頭文件, defines classes X, Y, Z
export module foo;
export using X = ::X; // export name X; retain all declarations
// of X from "some-header.h"
export Y f(); // export name f; retain all declarations
// of Y from "some-header.h"
// Z is not mentioned, so is discarded

// 或者
export import "another-header.h"; // another-header.h中的全部內容(除了宏)都會被導出

使用者:

import foo;
Y y = f();

import (推薦)

這種方式import的頭文件是以模塊方式編譯的。

export module foo; // 提供了一個foo的模塊
import "some_headers.h";
import &

這麼寫無需更改原來庫的任何內容,"some_headers.h"裏的所有聲明 + 宏會被原樣import進來。區別於現在的include的是:被import的對象是在一個單獨的TU裏翻譯的,不會受到主文件中符號的幹擾,可以更好的cache編譯結果。

這種方式優點是完全無痛,缺點是還保留了原先的header文件,適合處理一些不方便包/改動的第三方庫。

新代碼

下面這個代碼是一個moda模塊可能的代碼組織方式:

src/
|- moda/
|- functions.cpp
|- base.cpp
|- detail.cpp

base.cpp

export module moda:base; // users can import moda:base;

export void foo();
export int a;

functions.cpp

export module moda; // user can import moda

export import :base; // export all functions and values in base
// Moreover, moda.a is the same entity with moda.base.a
import :detail; // detail will not be exposed
export void additionalF() { implF(); }

detail.cpp

module moda:detail; //external user cannot import this module, only use through functions.cpps additionalF()
#include "some-macro.h" // legacy import, can import macro
import &; // atom-style import. Cant import macro in this way
void somelocalStuffs();
export void implF() {};

Coroutine

Coroutine

這次merge的是無棧版協程。直接看 What are coroutines in C++20? 這個

// Credits: http://www.modernescpp.com/index.php/coroutines

Acceptor acceptor{443};
while (true){
Socket socket= co_await acceptor.accept();
auto request= co_await socket.read();
auto response= handleRequest(request);
co_await socket.write(responste);
}

generator& generatorForNumbers(int begin, int inc= 1){
for (int i= begin;; i += inc){
co_yield i;
}
}

int main() {
std::cout &

std::polymorphic_allocator&

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0339r5.pdf?

www.open-std.org

之前有的polymorphic_allocator&為什麼還要存在&這樣一個類型參數?反正都要到處rebind,不如直接提供一個裸分配byte chunks的介面:polymophic_allocator&

剩下幾個之前的文章裏都介紹過:

Unwinding the stack?

zhuanlan.zhihu.com圖標

其實吧,這些大家都是巴不得17年就進來的(還包括networking)。現在搞到20年才進來,23年networking纔有可能,已經在大家期待之外了。要問怎麼看,只能說來得太晚了。

雖然編譯器很多功能都已經實現了,但是沒進標準,是沒有任何公司敢在真正的項目中用的。


好開心,可以直接從20開始入門了


Q:你會C++嗎?

A:會過。


如果我僅僅說好,這表達了我有多麼的被動。事實上,加的越多越好。

原來就是因為功能少,不方便,導致沒人用,都去搞其他語言了。

這回好了。徹底消滅精通c++的程序員。


到能用上要等多少年呢


這東西對於新手的准入門檻已經太高了,還是建議採取C+動態腳本語言來解決問題,代碼簡潔,邊界清晰,最主要是對於代碼的控制力強,非常舒服


推薦閱讀:
相關文章