こんにちは。
プロダクト&サービス事業部の青野です。
C++0xの一部の機能はGCC 4.3から使用することが可能になっています。そこで今回はC++0xで少し遊んでみようと思います。
C++0xとGCCの対応状況について
コンパイル環境の準備
Ubuntu 9.04で配布されているGCC(g++)は4.3系の為、autoがまだ実装されていません。とりあえずautoを試してみたいので7月22日にリリースされた4.4.1をソースからコンパイルしてインストールします。
- GCCのダウンロードと展開
$ mkdir ~/src $ cd ~/src $ wget ftp://ftp.dti.ad.jp/pub/lang/gcc/releases/gcc-4.4.1/gcc-4.4.1.tar.gz $ tar xvzf gcc-4.4.1.tar.gz
- GMPのダウンロードと展開
$ cd ~/src $ wget ftp://ftp.gmplib.org/pub/gmp-4.3.1/gmp-4.3.1.tar.gz $ tar xvzf gmp-4.3.1.tar.gz $ mv gmp-4.3.1 gcc-4.4.1/gmp
- MPFRのダウンロードと展開
$ cd ~/src $ wget http://www.mpfr.org/mpfr-current/mpfr-2.4.1.tar.gz $ tar xvzf mpfr-2.4.1.tar.gz $ mv mpfr-2.4.1 gcc-4.4.1/mpfr
- ビルドとインストール
$ mkdir ~/src/gccobj $ cd ~/src/gccobj $ ../gcc-4.4.1/configure $ make bootstrap $ sudo make install
C++0xソースのコンパイルと実行
Initializer Listとautoを試してみた
- サンプルソース(sample.cpp)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <iostream> #include <vector> void print(const std::vector<int>& v) { std::cout << "[print]" << std::endl; // std::vector<int>::const_iteratorだってautoでOK for (auto it = v.begin(); it != v.end(); ++it) { std::cout << *it << std::endl; } std::cout << std::endl; } void rprint(const std::vector<int>& v) { std::cout << "[rprint]" << std::endl; // std::vector<int>::const_reverse_iteratorだってautoでOK! for (auto it = v.rbegin(); it != v.rend(); ++it) { std::cout << *it << std::endl; } std::cout << std::endl; } int main() { std::vector<int> v = {1, 5, 10}; // std::vector<int>::iteratorだってautoでOK! for (auto it = v.begin(); it != v.end(); ++it) { std::cout << *it << std::endl; } std::cout << std::endl; print(v); rprint(v); return 0; }
- コンパイル
コンパイル時にC++0xの機能を使用する場合、コンパイル時に-std=gnu++0xオプションを指定する必要があります。$ g++ -std=gnu++0x sample.cpp
- 実行結果
$ ./a.out 1 5 10 [print] 1 5 10 [rprint] 10 5 1
autoに関しては多用すると可読性を損なう可能性がありますが、STLのコンテナクラスをイテレートする場合には可読性が上がっていい感じかなと思います。




