0%

Misc C++11 Feature Part 2

前一篇還是漏掉一些東西,因此才有這篇的存在。

Delegating constructors

在其他程式語言行之有年的玩意,終於加入C++11了。

1
2
3
4
5
6
class Num {
double v;
public:
Num(int v_) : Num((double)v_) {}
Num(double v_) : v(v_) {}
};

Raw String literals

也是在其他程式語言行之有年的觀念

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;
int main()
{
string normal_str = "First line.\nSecond line.\nEnd of message.\n";
string raw_str = R"(First line.\nSecond line.\nEnd of message.\n)";
cout << normal_str << endl;
cout << raw_str << endl;
return 0;
}

執行結果是

1
2
3
4
5
First line.
Second line.
End of message.

First line.\nSecond line.\nEnd of message.\n

Raw String中的特殊符號都不會被處理。

static_assert

在C++98的時代,就已經有Boost.StaticAssertLoki library可以在編譯期找出可能的錯誤。這項特色終於被加入語言之中。

1
2
static_assert( constant-expression, string-literal );
static_assert(sizeof(void *) == 4, "64-bit code generation is not supported.");

而沒有這項特色的C語言,就只能使用Stackoverflow的方式來做。

nullptr

原本NULL的定意識

1
2
3
#ifndef NULL
#define NULL 0
#endif

當如果有兩個同名函數

1
2
3
4
void foo(int) {}
void foo(void *) {}
foo(NULL); // Compile error
foo(nullptr); // foo(void *)

不過實際使用上,NULL比nullptr更顯眼,畢竟目前對nullptr做Syntax highlight的editor還不多。