[闲聊] Herb Sutter 展示 cppfront 编译器

楼主: nh60211as   2022-09-21 20:18:25
影片连结: https://www.youtube.com/watch?v=ELeZAKCN4tY
在今年的 CppCon 中,提出了多项 C++ 功能的 Herb Sutter
展示了他自己实验性的编译器:cppfront。
Github 连结:https://github.com/hsutter/cppfront
这个编译器可以将 Herb Sutter 设计的新语法 C++ syntax 2 (Cpp2)
转译成 C++ 语法 (类似 TypeScript > JavaScript)
以下是 Cpp2 语法:
main: () -> int = {
std::cout << "Hello " << name() << "\n";
}
name: () -> std::string = {
s: std::string = "world";
decorate(s);
return s;
}
decorate: (inout s: std::string) = {
s = "[" + s + "]";
}
看了语法有点类似 Kotlin 等比较年轻的程式语言,
提出一种新语法的目的不外乎是为了让 C++ 更安全、简单,
因为 C++ 为了语法相容性的关系很少提出破坏性的新语法,
因此很多人就算使用的 C++ 编译器可以支援新语法和工具了可能还在使用
raw pointer、NULL 这些旧时代的产物。
为了解决这些问题,Herb Sutter 提出的新语法默认便是以安全性为前提,
例如使用 new 产生 pointer 时 Cpp2 的语法
i := new<int>(0);
会使用 std::unique_ptr 来避免忘记释放内存导致的问题,
另外还有很多为了让 C++ 更安全、简单而提出的想法都可以在影片中看到。
感觉这些想法就算不会进入标准也应该可以作为写 C++ 程式的时候可以参考的做法。
个人满喜欢的是其中支援 pattern matching 的语法感觉可以让写 template function
的时候写法更易读:
main: () -> int = {
print_an_int("syzygy");
print_an_int(1);
print_an_int(1.1);
}
print_an_int: ( x: _ ) = {
std::cout
<< std::setw(30) << typeid(x).name()
<< " value is "
<< inspect x -> std::string {
is int = std::to_string(x as int);
is _ = "not an int";
}
<< "\n";
}
目前 cppfront 可以在各个主流的编译器下用 C++20 编译并使用,
Compiler Explorer 也已经支援 cppfront 了:
https://godbolt.org/z/bs371778a
作者: johnny94 (32767)   2022-09-21 20:29:00
跟carbon不知道那个会胜出XD
作者: NciscalA   2022-09-21 23:47:00
是说 Circle 也是在实作实验性语法,不过 cppfront 好像比较注重在编译器跟 ABI 的相容性?
作者: descent (“雄辩是银,沉默是金”)   2022-09-25 17:46:00
感谢分享
作者: ab4daa (nooooooooooooooooooo)   2022-09-29 08:48:00
所以以后可以把legacy code用这build了?
作者: yuichanprpr (有以ちゃん)   2022-09-29 16:37:00
虽然我都没用过 但这类次世代C目前是Rust最有利吧
作者: wulouise (在线上!=在电脑前)   2022-09-29 20:57:00
是新转旧不是旧转新..
作者: KMore   2022-10-02 02:14:00
用这怎不直接去rust
作者: OnlyRD (里巷人)   2022-11-25 02:31:00
c++最棒的地方就是你不想要安全只想要速度的时候...

Links booklink

Contact Us: admin [ a t ] ucptt.com